const readStream = fs.createReadStream(filepath);
const md5 = crypto.createHash('md5');
const ifNoneMatch = req.headers['if-none-match'];
readStream.on('data', data => {
md5.update(data);
});
readStream.on('end', () => {
let etag = md5.digest('hex');
if (ifNoneMatch === etag) {
resolve(true);
}
resolve(etag);
});
readStream.on('error', err => {
reject(err);
});
});
}
/**
* compress file
* @param {*} req
* @param {*} res
*/
compressHandler(req, res) {
const acceptEncoding = req.headers['accept-encoding'];
if (/bgzipb/.test(acceptEncoding)) {
res.setHeader('Content-Encoding', 'gzip');
return zlib.createGzip();
} else if (/bdeflateb/.test(acceptEncoding)) {
res.setHeader('Content-Encoding', 'deflate');
return zlib.createDeflate();
} else {
return false;
}
}
/**
* server start
*/
start() {
const server = http.createServer((req, res) => this.requestHandler(req, res));
server.listen(this.port, () => {
if (this.openbrowser) {
openbrowser(`http://${this.host}:${this.port}`);
}
console.log(`server started in http://${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 nodeconst 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' })









