实现说明
node:http 提供 createServer——内建表面,不涉及任何包。
演示用的数据放在这几个模块级绑定中:server。
使用要点
- 无需安装:
node:http随 Node.js 本体提供。 - 每一步打印都带着自己的标签:
listening:、closed cleanly。
常见问题
导入的模块是 npm 包吗?
不需要——node:http 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。
核心语句
res.end(JSON.stringify({ status: 'ok', path: req.url }));
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
console.log('listening:', port > 0);
// Closing frees the handle so the process can exit on its own
server.close(() => console.log('closed cleanly'));
});
代码示例
import { createServer } from 'node:http';
const server = createServer((req, res) => {
// writeHead sets status and headers first; res.end writes the body
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', path: req.url }));
});
// Port 0 asks the OS for a free ephemeral port instead of a fixed one
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
console.log('listening:', port > 0);
// Closing frees the handle so the process can exit on its own
server.close(() => console.log('closed cleanly'));
});