本篇文章主要介绍了实战node静态文件服务器的示例,分享给大家,具体如下:
- 读取静态文件
- 访问目录可以自动寻找下面的index.html文件,如果没有index.html则列出文件列表
- MIME类型支持
- 缓存支持/控制
- 支持gzip压缩
- Range支持,断点续传
- 全局命令执行
- 子进程运行
1. 创建服务读取静态文件
首先引入http模块,创建一个服务器,并监听配置端口:
const server = http.createServer();
// 监听请求
server.on('request',request.bind(this));
server.listen(config.port,() => {
console.log(<a href="https://www.jb51.cc/tag/jingtaiwenjian/" target="_blank" class="keywords">静态文件</a>服务启动成功,访问localhost:${con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>.port}
);
});
rush:js;">
const url = require('url');
const fs = require('fs');
function request(req,res) {
const { pathname } = url.parse(req.url); // 访问路径
const filepath = path.join(config.root,pathname); // 文件路径
fs.createReadStream(filepath).pipe(res); // 读取文件,并响应
}
支持寻找index.html:
rush:js;">
if (pathname === '/') {
const rootPath = path.join(config.root,'index.html');
try{
const indexStat = fs.statSync(rootPath);
if (indexStat) {
filepath = rootPath;
}
} catch(e) {
}
}
访问目录时,列出文件目录:
{
if (err) {
res.end('not found');
return;
}
if (stats.isDirectory()) {
let files = fs.readdirsync(filepath);
files = files.map(file => ({
name: file,url: path.join(pathname,file)
}));
let html = this.list()({
title: pathname,files
});
res.setHeader('Content-Type','text/html');
res.end(html);
}
}
html模板:
rush:js;">
function list() {
let tmpl = fs.readFileSync(path.resolve(__dirname,'template','list.html'),'utf8');
return handlebars.compile(tmpl);
}