如何通过Node.js搭建并深入理解命令行操作的静态服务器?

2026-04-08 22:081阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1180个文字,预计阅读时间需要5分钟。

如何通过Node.js搭建并深入理解命令行操作的静态服务器?

静态服务器 + 使用Node搭建一个可在任意目录下通过命令启动的简单http静态服务器 + 完整代码链接 + 安装:npm install yg-server -g + 启动:yg-server + 可通过以上命令安装、启动,来看一下最终结果“

静态服务器

使用node搭建一个可在任何目录下通过命令启动的一个简单${this.host}:${this.port}`); } console.log(`server started in ${this.host}:${this.port}`); }); }

请求处理

如何通过Node.js搭建并深入理解命令行操作的静态服务器?

  • 通过url模块解析请求路径,获取请求资源名
  • 获取请求的文件路径
  • 通过fs模块判断文件是否存在,这里分三种情况
    • 请求路径是一个文件夹,则调用responseDirectory处理
    • 请求路径是一个文件,则调用responseFile处理
    • 如果请求的文件不存在,则调用responseNotFound处理

requestHandler(req, res) { // 通过url模块解析请求路径,获取请求文件 const { pathname } = url.parse(req.url); // 获取请求的文件路径 const filepath = path.join(this.rootPath, pathname); // 判断文件是否存在 fs.stat(filepath, (err, stat) => { if (!err) { if (stat.isDirectory()) { this.responseDirectory(req, res, filepath, pathname); } else { this.responseFile(req, res, filepath, stat); } } else { this.responseNotFound(req, res); } }); }

处理请求的文件

  • 每次返回文件前,先调用前面我们写的cacheHandler模块来处理缓存
  • 如果有缓存则返回304
  • 如果不存在缓存,则设置文件类型,etag,跨域响应头
  • 调用compressHandler对返回的文件进行压缩处理
  • 返回资源

responseFile(req, res, filepath, stat) { this.cacheHandler(req, res, filepath).then( data => { if (data === true) { res.writeHead(304); res.end(); } else { res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8'); res.setHeader('Etag', data); this.cors && res.setHeader('Access-Control-Allow-Origin', '*'); const compress = this.compressHandler(req, res); if (compress) { fs.createReadStream(filepath) .pipe(compress) .pipe(res); } else { fs.createReadStream(filepath).pipe(res); } } }, error => { this.responseError(req, res, error); } ); }

处理请求的文件夹

  • 如果客户端请求的是一个文件夹,则返回的应该是该目录下的所有资源列表,而非一个具体的文件
  • 通过fs.readdir可以获取到该文件夹下面所有的文件或文件夹
  • 通过map来获取一个数组对象,是为了把该目录下的所有资源通过模版去渲染返回给客户端

responseDirectory(req, res, filepath, pathname) { fs.readdir(filepath, (err, files) => { if (!err) { const fileList = files.map(file => { const isDirectory = fs.statSync(filepath + '/' + file).isDirectory(); return { filename: file, url: path.join(pathname, file), isDirectory }; }); const html = handlebars.compile(templates.fileList)({ title: pathname, fileList }); res.setHeader('Content-Type', 'text/html'); res.end(html); } });

app.js完整代码

const ${this.host}:${this.port}`); } console.log(`server started in ${this.host}:${this.port}`); }); } } module.exports = StaticServer;

创建命令行工具

  • 首先在bin目录下创建一个config.js
  • 导出一些默认的配置

module.exports = { host: 'localhost', port: 3000, cors: true, openbrowser: true, index: 'index.html', charset: 'utf8' };

  • 然后创建一个static-server.js
  • 这里设置的是一些可执行的命令
  • 并实例化了我们最初在app.js里写的server类,将options作为参数传入
  • 最后调用server.start()来启动我们的服务器
  • 注意 #! /usr/bin/env node这一行不能省略哦

#! /usr/bin/env node const yargs = require('yargs'); const path = require('path'); const config = require('./config'); const StaticServer = require('../src/app'); const pkg = require(path.join(__dirname, '..', 'package.json')); const options = yargs .version(pkg.name + '@' + pkg.version) .usage('yg-server [options]') .option('p', { alias: 'port', describe: '设置服务器端口号', type: 'number', default: config.port }) .option('o', { alias: 'openbrowser', describe: '是否打开浏览器', type: 'boolean', default: config.openbrowser }) .option('n', { alias: 'host', describe: '设置主机名', type: 'string', default: config.host }) .option('c', { alias: 'cors', describe: '是否允许跨域', type: 'string', default: config.cors }) .option('v', { alias: 'version', type: 'string' }) .example('yg-server -p 8000 -o localhost', '在根目录开启监听8000端口的静态服务器') .help('h').argv; const server = new StaticServer(options); server.start();

入口文件

最后回到根目录下的index.js,将我们的模块导出,这样可以在根目录下通过node index来调试

module.exports = require('./bin/static-server');

配置命令

配置命令非常简单,进入到package.json文件里

加入一句话

"bin": { "yg-server": "bin/static-server.js" },

  • yg-server是启动该服务器的命令,可以自己定义
  • 然后执行npm link生成一个符号链接文件
  • 这样你就可以通过命令来执行自己的服务器了
  • 或者将包托管到npm上,然后全局安装,在任何目录下你都可以通过你设置的命令来开启一个静态服务器,在我们平时总会需要这样一个静态服务器

总结

写到这里基本上就写完了,另外还有几个模版文件,是用来在客户端展示的,可以看我的github,我就不贴了,只是一些html而已,你也可以自己设置,这个博客写多了是在是太卡了,字都打不动了。

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

本文共计1180个文字,预计阅读时间需要5分钟。

如何通过Node.js搭建并深入理解命令行操作的静态服务器?

静态服务器 + 使用Node搭建一个可在任意目录下通过命令启动的简单http静态服务器 + 完整代码链接 + 安装:npm install yg-server -g + 启动:yg-server + 可通过以上命令安装、启动,来看一下最终结果“

静态服务器

使用node搭建一个可在任何目录下通过命令启动的一个简单${this.host}:${this.port}`); } console.log(`server started in ${this.host}:${this.port}`); }); }

请求处理

如何通过Node.js搭建并深入理解命令行操作的静态服务器?

  • 通过url模块解析请求路径,获取请求资源名
  • 获取请求的文件路径
  • 通过fs模块判断文件是否存在,这里分三种情况
    • 请求路径是一个文件夹,则调用responseDirectory处理
    • 请求路径是一个文件,则调用responseFile处理
    • 如果请求的文件不存在,则调用responseNotFound处理

requestHandler(req, res) { // 通过url模块解析请求路径,获取请求文件 const { pathname } = url.parse(req.url); // 获取请求的文件路径 const filepath = path.join(this.rootPath, pathname); // 判断文件是否存在 fs.stat(filepath, (err, stat) => { if (!err) { if (stat.isDirectory()) { this.responseDirectory(req, res, filepath, pathname); } else { this.responseFile(req, res, filepath, stat); } } else { this.responseNotFound(req, res); } }); }

处理请求的文件

  • 每次返回文件前,先调用前面我们写的cacheHandler模块来处理缓存
  • 如果有缓存则返回304
  • 如果不存在缓存,则设置文件类型,etag,跨域响应头
  • 调用compressHandler对返回的文件进行压缩处理
  • 返回资源

responseFile(req, res, filepath, stat) { this.cacheHandler(req, res, filepath).then( data => { if (data === true) { res.writeHead(304); res.end(); } else { res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8'); res.setHeader('Etag', data); this.cors && res.setHeader('Access-Control-Allow-Origin', '*'); const compress = this.compressHandler(req, res); if (compress) { fs.createReadStream(filepath) .pipe(compress) .pipe(res); } else { fs.createReadStream(filepath).pipe(res); } } }, error => { this.responseError(req, res, error); } ); }

处理请求的文件夹

  • 如果客户端请求的是一个文件夹,则返回的应该是该目录下的所有资源列表,而非一个具体的文件
  • 通过fs.readdir可以获取到该文件夹下面所有的文件或文件夹
  • 通过map来获取一个数组对象,是为了把该目录下的所有资源通过模版去渲染返回给客户端

responseDirectory(req, res, filepath, pathname) { fs.readdir(filepath, (err, files) => { if (!err) { const fileList = files.map(file => { const isDirectory = fs.statSync(filepath + '/' + file).isDirectory(); return { filename: file, url: path.join(pathname, file), isDirectory }; }); const html = handlebars.compile(templates.fileList)({ title: pathname, fileList }); res.setHeader('Content-Type', 'text/html'); res.end(html); } });

app.js完整代码

const ${this.host}:${this.port}`); } console.log(`server started in ${this.host}:${this.port}`); }); } } module.exports = StaticServer;

创建命令行工具

  • 首先在bin目录下创建一个config.js
  • 导出一些默认的配置

module.exports = { host: 'localhost', port: 3000, cors: true, openbrowser: true, index: 'index.html', charset: 'utf8' };

  • 然后创建一个static-server.js
  • 这里设置的是一些可执行的命令
  • 并实例化了我们最初在app.js里写的server类,将options作为参数传入
  • 最后调用server.start()来启动我们的服务器
  • 注意 #! /usr/bin/env node这一行不能省略哦

#! /usr/bin/env node const yargs = require('yargs'); const path = require('path'); const config = require('./config'); const StaticServer = require('../src/app'); const pkg = require(path.join(__dirname, '..', 'package.json')); const options = yargs .version(pkg.name + '@' + pkg.version) .usage('yg-server [options]') .option('p', { alias: 'port', describe: '设置服务器端口号', type: 'number', default: config.port }) .option('o', { alias: 'openbrowser', describe: '是否打开浏览器', type: 'boolean', default: config.openbrowser }) .option('n', { alias: 'host', describe: '设置主机名', type: 'string', default: config.host }) .option('c', { alias: 'cors', describe: '是否允许跨域', type: 'string', default: config.cors }) .option('v', { alias: 'version', type: 'string' }) .example('yg-server -p 8000 -o localhost', '在根目录开启监听8000端口的静态服务器') .help('h').argv; const server = new StaticServer(options); server.start();

入口文件

最后回到根目录下的index.js,将我们的模块导出,这样可以在根目录下通过node index来调试

module.exports = require('./bin/static-server');

配置命令

配置命令非常简单,进入到package.json文件里

加入一句话

"bin": { "yg-server": "bin/static-server.js" },

  • yg-server是启动该服务器的命令,可以自己定义
  • 然后执行npm link生成一个符号链接文件
  • 这样你就可以通过命令来执行自己的服务器了
  • 或者将包托管到npm上,然后全局安装,在任何目录下你都可以通过你设置的命令来开启一个静态服务器,在我们平时总会需要这样一个静态服务器

总结

写到这里基本上就写完了,另外还有几个模版文件,是用来在客户端展示的,可以看我的github,我就不贴了,只是一些html而已,你也可以自己设置,这个博客写多了是在是太卡了,字都打不动了。

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