import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function httpRequest(port, rawPath) {
return new Promise((resolve, reject) => {
const req = http.request(
{ host: '127.0.0.1', port, path: rawPath, method: 'GET' },
(res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve({
status: res.statusCode,
contentType: res.headers['content-type'] || '',
body,
});
});
},
);
req.on('error', reject);
req.end();
});
}
async function main() {
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-web-module-'));
const htmlDoc = [
'<!DOCTYPE html>',
'<html lang="zh-CN">',
'<head><meta charset="utf-8"><title>BlueSky Web Lab</title></head>',
'<body><h1>Web Server Ready</h1><p>Static HTML response</p></body>',
'</html>',
].join('\n');
await fs.writeFile(path.join(tmpRoot, 'index.html'), htmlDoc, 'utf8');
const requestLog = [];
const server = http.createServer(async (req, res) => {
const rawPathPart = (req.url || '/').split('?')[0];
const rawPathname = decodeURIComponent(rawPathPart);
requestLog.push(rawPathname);
const rel = rawPathname.replace(/^\/+/, '') || 'index.html';
const resolvedRoot = path.resolve(tmpRoot);
const target = path.resolve(resolvedRoot, rel);
if (!target.startsWith(resolvedRoot + path.sep) && target !== resolvedRoot) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
try {
const content = await fs.readFile(target, 'utf8');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(content);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
}
});
const cases = [];
try {
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
// Case 1: static_file_server_200
const okRes = await httpRequest(port, '/index.html');
const actual1 = {
status: okRes.status,
contentType: okRes.contentType,
hasHeading: okRes.body.includes('<h1>Web Server Ready</h1>'),
loggedPath: requestLog[0],
};
const expected1 = {
status: 200,
contentType: 'text/html; charset=utf-8',
hasHeading: true,
loggedPath: '/index.html',
};
cases.push({
name: 'static_file_server_200',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: missing_file_returns_404
const missRes = await httpRequest(port, '/missing.html');
const actual2 = { status: missRes.status, body: missRes.body };
const expected2 = { status: 404, body: 'Not Found' };
cases.push({
name: 'missing_file_returns_404',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: path_traversal_guard_403
const travRes = await httpRequest(port, '/%2e%2e/%2e%2e/secret.txt');
const actual3 = { status: travRes.status, body: travRes.body };
const expected3 = { status: 403, body: 'Forbidden' };
cases.push({
name: 'path_traversal_guard_403',
passed: JSON.stringify(actual3) === JSON.stringify(expected3),
expected: expected3,
actual: actual3,
});
// Case 4: http_client_stream_and_fetch
const streamRes = await httpRequest(port, '/index.html');
const fetchRes = await fetch(`http://127.0.0.1:${port}/index.html`);
const fetchText = await fetchRes.text();
const titleMatch = fetchText.match(/<title>([^<]+)<\/title>/);
const actual4 = {
httpRequestStatus: streamRes.status,
fetchStatus: fetchRes.status,
sameBody: streamRes.body === fetchText,
byteLength: Buffer.byteLength(fetchText, 'utf8'),
title: titleMatch ? titleMatch[1] : null,
};
const expected4 = {
httpRequestStatus: 200,
fetchStatus: 200,
sameBody: true,
byteLength: Buffer.byteLength(htmlDoc, 'utf8'),
title: 'BlueSky Web Lab',
};
cases.push({
name: 'http_client_stream_and_fetch',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
await new Promise((resolve) => server.close(resolve));
await fs.rm(tmpRoot, { recursive: true, force: true });
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-web-module-lab/explore-web-module.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-web-module.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1077.zip