深入理解nodejs搭建静态服务器(实现命令行)

2020-06-17 07:04:16易采站长站整理

静态服务器

使用node搭建一个可在任何目录下通过命令启动的一个简单http静态服务器

完整代码链接

安装:

npm install yg-server -g

启动:

yg-server

可通过以上命令安装,启动,来看一下最终的效果

TODO

创建一个静态服务器
通过yargs来创建命令行工具
处理缓存
处理压缩

初始化

创建目录:mkdir static-server
进入到该目录:cd static-server
初始化项目:npm init
构建文件夹目录结构:

初始化静态服务器

首先在src目录下创建一个app.js
引入所有需要的包,非node自带的需要npm安装一下
初始化构造函数,options参数由命令行传入,后续会讲到

this.host 主机名
this.port 端口号
this.rootPath 根目录
this.cors 是否开启跨域
this.openbrowser 是否自动打开浏览器


const http = require('http'); // http模块
const url = require('url'); // 解析路径
const path = require('path'); // path模块
const fs = require('fs'); // 文件处理模块
const mime = require('mime'); // 解析文件类型
const crypto = require('crypto'); // 加密模块
const zlib = require('zlib'); // 压缩
const openbrowser = require('open'); //自动启动浏览器
const handlebars = require('handlebars'); // 模版
const templates = require('./templates'); // 用来渲染的模版文件

class StaticServer {
constructor(options) {
this.host = options.host;
this.port = options.port;
this.rootPath = process.cwd();
this.cors = options.cors;
this.openbrowser = options.openbrowser;
}
}

处理错误响应

在写具体业务前,先封装几个处理响应的函数,分别是错误的响应处理,没有找到资源的响应处理,在后面会调用这么几个函数来做响应

处理错误
返回状态码500
返回错误信息


responseError(req, res, err) {
res.writeHead(500);
res.end(`there is something wrong in th server! please try later!`);
}

处理资源未找到的响应
返回状态码404
返回一个404html


responseNotFound(req, res) {
// 这里是用handlerbar处理了一个模版并返回,这个模版只是单纯的一个写着404html
const html = handlebars.compile(templates.notFound)();
res.writeHead(404, {
'Content-Type': 'text/html'