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

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

} 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 http = require('http');
const url = require('url');
const path = require('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;