支持功能:javascript
首先引入http模块,建立一个服务器,并监听配置端口:html
const http = require('http');
const server = http.createServer();
// 监听请求
server.on('request', request.bind(this));
server.listen(config.port, () => {
console.log(`静态文件服务启动成功, 访问localhost:${config.port}`);
});
复制代码
写一个fn专门处理请求, 返回静态文件, url模块获取路径:java
const url = require('url');
const fs = require('fs');
function request(req, res) {
const { pathname } = url.parse(req.url); // 访问路径
const filepath = path.join(config.root, pathname); // 文件路径
fs.createReadStream(filepath).pipe(res); // 读取文件,并响应
}
复制代码
支持寻找index.html:node
if (pathname === '/') {
const rootPath = path.join(config.root, 'index.html');
try{
const indexStat = fs.statSync(rootPath);
if (indexStat) {
filepath = rootPath;
}
} catch(e) {
}
}
复制代码
访问目录时,列出文件目录:git
fs.stat(filepath, (err, stats) => {
if (err) {
res.end('not found');
return;
}
if (stats.isDirectory()) {
let files = fs.readdirSync(filepath);
files = files.map(file => ({
name: file,
url: path.join(pathname, file)
}));
let html = this.list()({
title: pathname,
files
});
res.setHeader('Content-Type', 'text/html');
res.end(html);
}
}
复制代码
html模板:github
function list() {
let tmpl = fs.readFileSync(path.resolve(__dirname, 'template', 'list.html'), 'utf8');
return handlebars.compile(tmpl);
}
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{title}}</title>
</head>
<body>
<h1>hope-server静态文件服务器</h1>
<ul>
{{#each files}}
<li>
<a href={{url}}>{{name}}</a>
</li>
{{/each}}
</ul>
</body>
</html>
复制代码
利用mime模块获得文件类型,并设置编码:npm
res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');
复制代码
http协议缓存:json
handleCache(req, res, stats, hash) {
// 当资源过时时, 客户端发现上一次请求资源,服务器有发送Last-Modified, 则再次请求时带上if-modified-since
const ifModifiedSince = req.headers['if-modified-since'];
// 服务器发送了etag,客户端再次请求时用If-None-Match字段来询问是否过时
const ifNoneMatch = req.headers['if-none-match'];
// http1.1内容 max-age=30 为强行缓存30秒 30秒内再次请求则用缓存 private 仅客户端缓存,代理服务器不可缓存
res.setHeader('Cache-Control', 'private,max-age=30');
// http1.0内容 做用与Cache-Control一致 告诉客户端什么时间,资源过时 优先级低于Cache-Control
res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toGMTString());
// 设置ETag 根据内容生成的hash
res.setHeader('ETag', hash);
// 设置Last-Modified 文件最后修改时间
const lastModified = stats.ctime.toGMTString();
res.setHeader('Last-Modified', lastModified);
// 判断ETag是否过时
if (ifNoneMatch && ifNoneMatch != hash) {
return false;
}
// 判断文件最后修改时间
if (ifModifiedSince && ifModifiedSince != lastModified) {
return false;
}
// 若是存在且相等,走缓存304
if (ifNoneMatch || ifModifiedSince) {
res.writeHead(304);
res.end();
return true;
} else {
return false;
}
}
复制代码
客户端发送内容,经过请求头里Accept-Encoding: gzip, deflate告诉服务器支持哪些压缩格式,服务器根据支持的压缩格式,压缩内容。如服务器不支持,则不压缩。缓存
getEncoding(req, res) {
const acceptEncoding = req.headers['accept-encoding'];
// gzip和deflate压缩
if (/\bgzip\b/.test(acceptEncoding)) {
res.setHeader('Content-Encoding', 'gzip');
return zlib.createGzip();
} else if (/\bdeflate\b/.test(acceptEncoding)) {
res.setHeader('Content-Encoding', 'deflate');
return zlib.createDeflate();
} else {
return null;
}
}
复制代码
服务器经过请求头中的Range: bytes=0-xxx来判断是不是作Range请求,若是这个值存在并且有效,则只发回请求的那部分文件内容,响应的状态码变成206,表示Partial Content,并设置Content-Range。若是无效,则返回416状态码,代表Request Range Not Satisfiable。若是不包含Range的请求头,则继续经过常规的方式响应。bash
getStream(req, res, filepath, statObj) {
let start = 0;
let end = statObj.size - 1;
const range = req.headers['range'];
if (range) {
res.setHeader('Accept-Range', 'bytes');
res.statusCode = 206;//返回整个内容的一块
let result = range.match(/bytes=(\d*)-(\d*)/);
if (result) {
start = isNaN(result[1]) ? start : parseInt(result[1]);
end = isNaN(result[2]) ? end : parseInt(result[2]) - 1;
}
}
return fs.createReadStream(filepath, {
start, end
});
}
复制代码
经过npm link实现
npm link命令经过连接目录和可执行文件,实现npm包命令的全局可执行。
package.json里面配置
{
bin: {
"hope-server": "bin/hope"
}
}
复制代码
在项目下面建立bin目录 hope文件, 利用yargs配置命令行传参数
// 告诉电脑用node运行个人文件
#! /usr/bin/env node
const yargs = require('yargs');
const init = require('../src/index.js');
const argv = yargs.option('d', {
alias: 'root',
demand: 'false',
type: 'string',
default: process.cwd(),
description: '静态文件根目录'
}).option('o', {
alias: 'host',
demand: 'false',
default: 'localhost',
type: 'string',
description: '配置监听的主机'
}).option('p', {
alias: 'port',
demand: 'false',
type: 'number',
default: 8080,
description: '配置端口号'
}).option('c', {
alias: 'child',
demand: 'false',
type: 'boolean',
default: false,
description: '是否子进程运行'
})
.usage('hope-server [options]')
.example(
'hope-server -d / -p 9090 -o localhost', '在本机的9090端口上监听客户端的请求'
).help('h').argv;
// 启动服务
init(argv);
复制代码
经过spawn实现
index.js
const { spawn } = require('child_process');
const Server = require('./hope');
function init(argv) {
// 若是配置为子进程开启服务
if (argv.child) {
//子进程启动服务
const child = spawn('node', ['hope.js', JSON.stringify(argv)], {
cwd: __dirname,
detached: true,
stdio: 'inherit'
});
//后台运行
child.unref();
//退出主线程,让子线程单独运行
process.exit(0);
} else {
const server = new Server(argv);
server.start();
}
}
module.exports = init;
复制代码
hope.js
if (process.argv[2] && process.argv[2].startsWith('{')) {
const argv = JSON.parse(process.argv[2]);
const server = new Hope(argv);
server.start();
}
复制代码
源码地址: hope-server
npm install hope-server -g
复制代码
进入任意目录
hope-server
复制代码