实战node静态文件服务器的示例代码
本篇文章主要介绍了实战node静态文件服务器的示例,分享给大家,具体如下:
支持功能:
- 读取静态文件
- 访问目录可以自动寻找下面的index.html文件,如果没有index.html则列出文件列表
- MIME类型支持
- 缓存支持/控制
- 支持gzip压缩
- Range支持,断点续传
- 全局命令执行
- 子进程运行
1.创建服务读取静态文件
首先引入http模块,创建一个服务器,并监听配置端口:
consthttp=require('http');
constserver=http.createServer();
//监听请求
server.on('request',request.bind(this));
server.listen(config.port,()=>{
console.log(`静态文件服务启动成功,访问localhost:${config.port}`);
});
写一个fn专门处理请求,返回静态文件,url模块获取路径:
consturl=require('url');
constfs=require('fs');
functionrequest(req,res){
const{pathname}=url.parse(req.url);//访问路径
constfilepath=path.join(config.root,pathname);//文件路径
fs.createReadStream(filepath).pipe(res);//读取文件,并响应
}
支持寻找index.html:
if(pathname==='/'){
constrootPath=path.join(config.root,'index.html');
try{
constindexStat=fs.statSync(rootPath);
if(indexStat){
filepath=rootPath;
}
}catch(e){
}
}
访问目录时,列出文件目录:
fs.stat(filepath,(err,stats)=>{
if(err){
res.end('notfound');
return;
}
if(stats.isDirectory()){
letfiles=fs.readdirSync(filepath);
files=files.map(file=>({
name:file,
url:path.join(pathname,file)
}));
lethtml=this.list()({
title:pathname,
files
});
res.setHeader('Content-Type','text/html');
res.end(html);
}
}
html模板:
functionlist(){
lettmpl=fs.readFileSync(path.resolve(__dirname,'template','list.html'),'utf8');
returnhandlebars.compile(tmpl);
}
{{title}} hope-server静态文件服务器
{{#eachfiles}}
- {{/each}}
{{name}}