Node.js 提供 fs、http 等核心模块。异步 API 可以避免阻塞事件循环。

本节要点

  • fs/promises 提供 Promise 版本的文件 API。
  • http.createServer 可以创建 HTTP 服务。
  • fetch 可以发送网络请求。

代码示例

import { readFile } from "node:fs/promises";
import http from "node:http";

const server = http.createServer(async (req, res) => {
  const html = await readFile("./index.html", "utf8");
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  res.end(html);
});

server.listen(3000, () => {
  console.log("http://127.0.0.1:3000");
});