当前位置:Gxlcms > PHP教程 > node静态文件服务器详解

node静态文件服务器详解

时间:2021-07-01 10:21:17 帮助过:37人阅读

支持功能:

  1. 读取静态文件

  2. 访问目录可以自动寻找下面的index.html文件, 如果没有index.html则列出文件列表

  3. MIME类型支持

  4. 缓存支持/控制

  5. 支持gzip压缩

  6. Range支持,断点续传

  7. 全局命令执行

  8. 子进程运行

本文主要和大家介绍了实战node静态文件服务器的示例,希望能帮助到大家。

1. 创建服务读取静态文件

首先引入http模块,创建一个服务器,并监听配置端口:


  1. const http = require('http');
  2. const server = http.createServer();
  3. // 监听请求
  4. server.on('request', request.bind(this));
  5. server.listen(config.port, () => {
  6. console.log(`静态文件服务启动成功, 访问localhost:${config.port}`);
  7. });

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


  1. const url = require('url');
  2. const fs = require('fs');
  3. function request(req, res) {
  4. const { pathname } = url.parse(req.url); // 访问路径
  5. const filepath = path.join(config.root, pathname); // 文件路径
  6. fs.createReadStream(filepath).pipe(res); // 读取文件,并响应
  7. }

支持寻找index.html:


  1. if (pathname === '/') {
  2. const rootPath = path.join(config.root, 'index.html');
  3. try{
  4. const indexStat = fs.statSync(rootPath);
  5. if (indexStat) {
  6. filepath = rootPath;
  7. }
  8. } catch(e) {
  9. }
  10. }

访问目录时,列出文件目录:


  1. fs.stat(filepath, (err, stats) => {
  2. if (err) {
  3. res.end('not found');
  4. return;
  5. }
  6. if (stats.isDirectory()) {
  7. let files = fs.readdirSync(filepath);
  8. files = files.map(file => ({
  9. name: file,
  10. url: path.join(pathname, file)
  11. }));
  12. let html = this.list()({
  13. title: pathname,
  14. files
  15. });
  16. res.setHeader('Content-Type', 'text/html');
  17. res.end(html);
  18. }
  19. }

html模板:


  1. function list() {
  2. let tmpl = fs.readFileSync(path.resolve(__dirname, 'template', 'list.html'), 'utf8');
  3. return handlebars.compile(tmpl);
  4. }


  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>{{title}}</title>
  8. </head>
  9. <body>
  10. <h1>hope-server静态文件服务器</h1>
  11. <ul>
  12. {{#each files}}
  13. <li>
  14. <a href={{url}}>{{name}}</a>
  15. </li>
  16. {{/each}}
  17. </ul>
  18. </body>
  19. </html>

2.MIME类型支持

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


  1. res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');

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值


  1. handleCache(req, res, stats, hash) {
  2. // 当资源过期时, 客户端发现上一次请求资源,服务器有发送Last-Modified, 则再次请求时带上if-modified-since
  3. const ifModifiedSince = req.headers['if-modified-since'];
  4. // 服务器发送了etag,客户端再次请求时用If-None-Match字段来询问是否过期
  5. const ifNoneMatch = req.headers['if-none-match'];
  6. // http1.1内容 max-age=30 为强行缓存30秒 30秒内再次请求则用缓存 private 仅客户端缓存,代理服务器不可缓存
  7. res.setHeader('Cache-Control', 'private,max-age=30');
  8. // http1.0内容 作用与Cache-Control一致 告诉客户端什么时间,资源过期 优先级低于Cache-Control
  9. res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toGMTString());
  10. // 设置ETag 根据内容生成的hash
  11. res.setHeader('ETag', hash);
  12. // 设置Last-Modified 文件最后修改时间
  13. const lastModified = stats.ctime.toGMTString();
  14. res.setHeader('Last-Modified', lastModified);
  15. // 判断ETag是否过期
  16. if (ifNoneMatch && ifNoneMatch != hash) {
  17. return false;
  18. }
  19. // 判断文件最后修改时间
  20. if (ifModifiedSince && ifModifiedSince != lastModified) {
  21. return false;
  22. }
  23. // 如果存在且相等,走缓存304
  24. if (ifNoneMatch || ifModifiedSince) {
  25. res.writeHead(304);
  26. res.end();
  27. return true;
  28. } else {
  29. return false;
  30. }
  31. }

4.压缩

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


  1. getEncoding(req, res) {
  2. const acceptEncoding = req.headers['accept-encoding'];
  3. // gzip和deflate压缩
  4. if (/\bgzip\b/.test(acceptEncoding)) {
  5. res.setHeader('Content-Encoding', 'gzip');
  6. return zlib.createGzip();
  7. } else if (/\bdeflate\b/.test(acceptEncoding)) {
  8. res.setHeader('Content-Encoding', 'deflate');
  9. return zlib.createDeflate();
  10. } else {
  11. return null;
  12. }
  13. }

5.断点续传

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


  1. getStream(req, res, filepath, statObj) {
  2. let start = 0;
  3. let end = statObj.size - 1;
  4. const range = req.headers['range'];
  5. if (range) {
  6. res.setHeader('Accept-Range', 'bytes');
  7. res.statusCode = 206;//返回整个内容的一块
  8. let result = range.match(/bytes=(\d*)-(\d*)/);
  9. if (result) {
  10. start = isNaN(result[1]) ? start : parseInt(result[1]);
  11. end = isNaN(result[2]) ? end : parseInt(result[2]) - 1;
  12. }
  13. }
  14. return fs.createReadStream(filepath, {
  15. start, end
  16. });
  17. }

6.全局命令执行

通过npm link实现

  1. 为npm包目录创建软链接,将其链到{prefix}/lib/node_modules/

  2. 为可执行文件(bin)创建软链接,将其链到{prefix}/bin/{name}

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

package.json里面配置


  1. {
  2. bin: {
  3. "hope-server": "bin/hope"
  4. }
  5. }

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


  1. // 告诉电脑用node运行我的文件
  2. #! /usr/bin/env node
  3. const yargs = require('yargs');
  4. const init = require('../src/index.js');
  5. const argv = yargs.option('d', {
  6. alias: 'root',
  7. demand: 'false',
  8. type: 'string',
  9. default: process.cwd(),
  10. description: '静态文件根目录'
  11. }).option('o', {
  12. alias: 'host',
  13. demand: 'false',
  14. default: 'localhost',
  15. type: 'string',
  16. description: '配置监听的主机'
  17. }).option('p', {
  18. alias: 'port',
  19. demand: 'false',
  20. type: 'number',
  21. default: 8080,
  22. description: '配置端口号'
  23. }).option('c', {
  24. alias: 'child',
  25. demand: 'false',
  26. type: 'boolean',
  27. default: false,
  28. description: '是否子进程运行'
  29. })
  30. .usage('hope-server [options]')
  31. .example(
  32. 'hope-server -d / -p 9090 -o localhost', '在本机的9090端口上监听客户端的请求'
  33. ).help('h').argv;
  34. // 启动服务
  35. init(argv);

7.子进程运行

通过spawn实现

index.js


  1. const { spawn } = require('child_process');
  2. const Server = require('./hope');
  3. function init(argv) {
  4. // 如果配置为子进程开启服务
  5. if (argv.child) {
  6. //子进程启动服务
  7. const child = spawn('node', ['hope.js', JSON.stringify(argv)], {
  8. cwd: __dirname,
  9. detached: true,
  10. stdio: 'inherit'
  11. });
  12. //后台运行
  13. child.unref();
  14. //退出主线程,让子线程单独运行
  15. process.exit(0);
  16. } else {
  17. const server = new Server(argv);
  18. server.start();
  19. }
  20. }
  21. module.exports = init;
  22. hope.js
  23. if (process.argv[2] && process.argv[2].startsWith('{')) {
  24. const argv = JSON.parse(process.argv[2]);
  25. const server = new Hope(argv);
  26. server.start();
  27. }

8.源码及测试

源码地址: hope-server


  1. npm install hope-server -g

进入任意目录


  1. hope-server

相关推荐:

使用nodejs、Python写的一个简易HTTP静态文件服务器

使用nodejs、Python写的一个简易HTTP静态文件服务器_node.js

Node.js静态文件服务器改进版_node.js

以上就是node静态文件服务器详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行