实战node静态文件服务器的示例代码

本篇文章主要介绍了实战node静态文件服务器的示例,分享给大家,具体如下:

支持功能:

  1. 读取静态文件
  2. 访问目录可以自动寻找下面的index.html文件,如果没有index.html则列出文件列表
  3. MIME类型支持
  4. 缓存支持/控制
  5. 支持gzip压缩
  6. Range支持,断点续传
  7. 全局命令执行
  8. 子进程运行

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});
});

一个fn专门处理请求,返回静态文件,url模块获取路径:

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); }
rush:xhtml;"> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width,initial-scale=1.0"> <Meta http-equiv="X-UA-Compatible" content="ie=edge"> {{title}}

hope-server静态文件服务器

2.MIME类型支持

利用模块得到文件类型,并设置编码:

3.缓存支持

http协议缓存:

Cache-Control: http1.1内容,告诉客户端如何缓存数据,以及规则

  1. private 客户端可以缓存
  2. public 客户端和代理服务器都可以缓存
  3. max-age=60 缓存内容将在60秒后失效
  4. no-cache 需要使用对比缓存验证数据,强制向源服务器再次验证
  5. no-store 所有内容都不会缓存,强制缓存和对比缓存都不会触发

Expires: http1.0内容,cache-control会覆盖,告诉客户端缓存什么时候过期

ETag: 内容的hash值 下一次客户端请求在请求头里添加if-none-match: etag值

Last-Modified: 最后的修改时间 下一次客户端请求在请求头里添加if-modified-since: Last-Modified值

// 判断ETag是否过期
if (ifNoneMatch && ifNoneMatch != hash) {
return false;
}
// 判断文件最后修改时间
if (ifModifiedSince && ifModifiedSince != lastModified) {
return false;
}
// 如果存在且相等,走缓存304
if (ifNoneMatch || ifModifiedSince) {
res.writeHead(304);
res.end();
return true;
} else {
return false;
}
}

4.压缩

客户端发送内容,通过请求头里Accept-Encoding: gzip,deflate告诉服务器支持哪些压缩格式,服务器根据支持的压缩格式,压缩内容。如服务器不支持,则不压缩。

5.断点续传

服务器通过请求头中的Range: bytes=0-xxx来判断是否是做Range请求,如果这个值存在而且有效,则只发回请求的那部分文件内容,响应的状态码变成206,表示Partial Content,并设置Content-Range。如果无效,则返回416状态码,表明Request Range Not Satisfiable。如果不包含Range的请求头,则继续通过常规的方式响应。

6.全局命令执行

通过npm link实现

  1. 为npm包目录创建软链接,将其链到{prefix}/lib/node_modules/
  2. 为可执行文件(bin)创建软链接,将其链到{prefix}/bin/{name}

npm link命令通过链接目录和可执行文件,实现npm包命令的全局可执行。

package.json里面配置

在项目下面创建bin目录 hope文件,利用yargs配置命令行传参数

const yargs = require('yargs');
const init = require('../src/index.js');
const argv = yargs.option('d',{
alias: 'root',demand: 'false',type: 'string',default: process.cwd(),description: '静态文件根目录'
}).option('o',{
alias: 'host',default: 'localhost',description: '配置监听的主机'
}).option('p',{
alias: 'port',type: 'number',default: 8080,description: '配置端口号'
}).option('c',{
alias: 'child',type: 'boolean',default: false,description: '是否子进程运行'
})
.usage('hope-server [options]')
.example(
'hope-server -d / -p 9090 -o localhost','在本机的9090端口上监听客户端的请求'
).help('h').argv;

// 启动服务
init(argv);

7.子进程运行

通过spawn实现

index.js

function init(argv) {
// 如果配置为子进程开启服务
if (argv.child) {
//子进程启动服务
const child = spawn('node',['hope.js',JSON.stringify(argv)],{
cwd: __dirname,detached: true,stdio: 'inherit'
});

//后台运行
child.unref();
//退出主线程,让子线程单独运行
process.exit(0);
} else {
const server = new Server(argv);
server.start();
}
}

module.exports = init;
hope.js
if (process.argv[2] && process.argv[2].startsWith('{')) {
const argv = JSON.parse(process.argv[2]);
const server = new Hope(argv);
server.start();
}

8.源码及测试

源码地址:

rush:bash;"> npm install hope-server -g

进入任意目录

rush:bash;"> hope-server

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...