70 行 Node.js 写一个够用的静态服务器:ETag、Range、gzip 都要有
本地预览构建产物、给同事内网丢个包,开 nginx 有点重,装个框架又得背一堆依赖。手写一个七十来行的静态服务器其实够用,前提是把四个 HTTP 细节做对:Content-Type、304、206、gzip,外加一条安全底线。
边界先划清:只服务构建产物,单机本地或内网,不面向公网流量;不做 HTTP/2,不做目录索引,不做 TLS。
完整代码
import http from 'node:http';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import zlib from 'node:zlib';
const ROOT = path.resolve('public');
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg' };
http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
let rel = decodeURIComponent(url.pathname);
if (rel.endsWith('/')) rel += 'index.html';
const file = path.join(ROOT, rel);
if (!file.startsWith(ROOT + path.sep)) return send(res, 403); // 防目录穿越
const stat = await fsp.stat(file).catch(() => null);
if (!stat?.isFile()) return send(res, 404);
const etag = `W/"${stat.size.toString(16)}-${Math.floor(stat.mtimeMs).toString(16)}"`;
const type = MIME[path.extname(file)] || 'application/octet-stream';
if (req.headers['if-none-match'] === etag) { // 304
return res.writeHead(304, { ETag: etag }).end();
}
const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '');
if (m) { // 206 / 416
const start = m[1] ? +m[1] : 0;
const end = m[2] ? +m[2] : stat.size - 1;
if (start > end || end >= stat.size) {
return res.writeHead(416, { 'Content-Range': `bytes */${stat.size}` }).end();
}
res.writeHead(206, {
'Content-Type': type,
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
'Content-Length': end - start + 1,
'Accept-Ranges': 'bytes',
ETag: etag,
});
return fs.createReadStream(file, { start, end }).pipe(res);
}
const text = /^(text\/|application\/(json|javascript))/.test(type);
if (text && /\bgzip\b/.test(req.headers['accept-encoding'] || '')) {
res.writeHead(200, { 'Content-Type': type, 'Content-Encoding': 'gzip',
ETag: etag, Vary: 'Accept-Encoding' });
return fs.createReadStream(file).pipe(zlib.createGzip()).pipe(res);
}
res.writeHead(200, { 'Content-Type': type, 'Content-Length': stat.size, ETag: etag });
fs.createReadStream(file).pipe(res);
}).listen(8080);
const send = (res, code) =>
res.writeHead(code, { 'Content-Type': 'text/plain' }).end(String(code));
四个细节,错一个都不算够用
ETag 用 size + mtime 就够。 内容哈希更准,但每次请求都算摘要,代价比省下的带宽高。弱 ETag(W/ 前缀)已经能判断文件改没改,命中 If-None-Match 就回 304 空 body。
Range 必须处理 416。 只写 206、忘了非法区间,播放器拖进度条时请求越界,服务端还回 200 全量,视频就黑屏或从头缓冲。正确做法是回 416 加 Content-Range: bytes */文件长度。
只压文本,并且带上 Vary: Accept-Encoding。 图片字体别再压,gzip 对已压缩格式几乎无效。少了 Vary,中间缓存可能把 gzip 版本发给不支持压缩的客户端,排查起来非常费劲。
目录穿越:URL 帮你挡一半。 WHATWG 的 URL 解析器会把 %2e%2e 当 .. 规范化掉,所以 /%2e%2e/server.mjs 到 pathname 时已经变成 /server.mjs,天然失效;但把斜杠一起编码的 /%2e%2e%2fserver.mjs 解出来仍是 ../server.mjs,规范化管不着。所以 path.join 之后必须再做一次前缀校验,且不能放在 decodeURIComponent 之前。
实测结果
| 场景 | 状态码 | 关键响应头 |
|---|---|---|
| 首次 GET | 200 | Content-Encoding: gzip |
| 带 If-None-Match | 304 | 空 body |
Range: bytes=0-9 |
206 | Content-Range: bytes 0-9/194 |
| 编码斜杠穿越 | 403 | — |
| 不存在的文件 | 404 | — |
一个反直觉的发现:用 fetch 发 /%2e%2e/server.mjs,客户端自己先把路径规范化了,测出来是 404 而不是 403。要看真实行为得用裸 socket 发原始请求,否则你测的是客户端的规范化逻辑。
生产环境别用它
没有零拷贝,没有 HTTP/2 和 TLS,没有连接超时与并发限制——一个慢连接就能长期占住 socket;缓存协商也只做了 ETag。它适合本地预览、内网分发、CI 验收产物,这些场景下比装一套 nginx 快得多。
小结
写这七十行的收获不在代码,而在于把「一个静态服务器至少要满足哪些 HTTP 约定」过了一遍。下次配 nginx 时,也知道那些 add_header 到底在补什么。
- 点赞
- 收藏
- 关注作者
评论(0)