蓝色天空网mbsky.com · 知识 · 实践 · 创造Node.js · 本地阅读预览
教程 / 后端开发 / Node.js

Node.js 内置模块

全景梳理 Node.js 27 个核心内置模块的功能定位、加载方式与跨平台优势,重点解析 fs、path、http、events、os、crypto、net、vm 等高频模块,并附 Node.js v24.22.3 实测验证。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

内置模块定位与全景速览

Node.js 内置模块随运行时一同发布,无需借助 `npm` 安装即可直接加载,提供文件系统、网络协议、进程与线程、加解密等基础系统能力。CommonJS 中通过 `require('fs')` 导入,现代代码亦推荐使用带 `node:` 前缀的写法(如 `import fs from 'node:fs'`)以显式区分内置核心模块与第三方依赖;下方参考表汇总了 27 个主要内置模块,本站实测确认这 27 个模块名在 Node.js v24.22.3 的 `module.builtinModules` 中全部存在。

五大高频内置模块实测详解

`fs` 模块负责本地文件读写、目录创建/删除、文件变化监听及元数据查询,兼有同步与异步两套接口。本站实测在临时目录中同步写入 `'Hello Node.js'` 后异步读出完全一致,且在结束后自动清理临时目录。

`path` 模块屏蔽不同操作系统的路径分隔符差异,核心方法包括 `path.join()` 拼接片段、`path.resolve()` 生成规范绝对路径、`path.basename()` 提取文件名以及 `path.extname()` 提取扩展名(本站实测对 `'index.html'` 返回 `'.html'`,对 POSIX 路径拼接得 `'/home/user/project/files/example.txt'`)。

`http` 模块同时支持构建 HTTP 服务器、发起客户端请求以及处理请求头/响应体。本站在本地回环 `127.0.0.1:0` 启动 `http.createServer` 服务并用内置 `fetch()` 请求,实测返回状态码 `200` 与正文 `'Hello Node.js Server'`。

`events` 模块是 Node.js 事件驱动架构的核心,通过继承或实例化 `EventEmitter` 类,使用 `on`/`once` 注册监听器并用 `emit` 派发事件。本站实测普通监听器与一次性 `once` 监听器重复触发后记录为 `['on:a', 'once']`。

`os` 模块暴露操作系统底层运行信息,包括 CPU 核列表(`os.cpus()`)、总内存与空闲内存(`os.totalmem()`/`os.freemem()`)、网络接口与系统临时目录(`os.tmpdir()`)。本站实测各项指标均在离线环境下正常返回正数或非空路径。

其他核心模块、加载规范与工程优势

除上述五大模块外,开发常配合使用:`util`(类型检查、字符串格式化、回调转 Promise 与历史继承工具)、`crypto`(SHA-256 哈希、HMAC、对称/非对称加解密与数字签名;注意 Node.js v24 已移除旧版无 IV 的 `createCipher`/`createDecipher`,须使用 `createCipheriv`/`createDecipheriv`)、`stream`(数据流抽象)、`child_process`(子进程调度)与 `url`(WHATWG `URL` 解析与格式化)。此外本站在本地离线环境还实测了 `zlib` Gzip 往返、`net` 回环 TCP 通信(`'echo:ping'`)、`vm.runInContext` 求值(`35`)、`perf_hooks` 单调计时与 `worker_threads.isMainThread`。

加载内置模块时需牢记四点:直接写模块名不加相对路径、名称严格区分大小写、无需额外安装,且不同 Node.js 大版本可能增删部分模块(如旧版 `domain` 已标记废弃)。内置模块之所以成为首选基础层,得益于其紧贴运行时的高性能、长期测试验证的稳定性、开箱即用免安装、跨平台一致体验以及完备的官方文档支持。

Node.js 主要内置核心模块速查表

模块名称核心职责常用类与方法典型应用场景
fs (File System)文件系统操作readFile, writeFile, mkdir, readdir, createReadStream, createWriteStream文件读写、目录管理与流式大文件处理
path跨平台路径解析join, resolve, dirname, basename, extname拼接与拆解文件路径,屏蔽系统分隔符差异
httpHTTP 服务端与客户端createServer, request, get构建 Web 服务、代理与接口通信
https基于 TLS 的安全 HTTPcreateServer, request构建加密 HTTPS 服务与客户端请求
urlURL 解析与构造URL, URLSearchParams, format, parse(遗留)解析请求地址与查询参数
querystring查询字符串编解码parse, stringify解析与序列化 URL 查询串及表单体(新代码亦可用 URLSearchParams)
os操作系统运行信息cpus, freemem, totalmem, homedir, hostname, tmpdir采集宿主机硬件、内存与临时目录信息
events事件发布与订阅EventEmitter, on, emit, once自定义异步事件模型与组件解耦
stream流式数据抽象接口Readable, Writable, Duplex, Transform, pipe分块传输大文件、网络流与管道转换
crypto密码学与摘要算法createHash, createHmac, createCipheriv, randomBytes(旧 createCipher 在 v24 已移除)摘要校验、对称/非对称加解密与安全随机数
zlib压缩与解压流createGzip, createGunzip, gzipSync, gunzipSync, createDeflateHTTP 响应压缩与归档数据解压
util通用辅助与调试工具promisify, callbackify, format, inspect, types回调转 Promise、对象检查与类型断言
child_process外部子进程调度exec, execFile, spawn, fork运行外部命令行工具或衍生 Node 子进程
cluster多进程集群管理fork, isPrimary(旧 isMaster 已弃用), isWorker利用多核 CPU 分担端口连接负载
dns域名系统查询lookup, resolve, reverse域名正向与反向解析
domain历史异步错误分组(已弃用)create, run, add早期用于集中捕获异步错误,现代代码改用 Promise/AsyncLocalStorage
net底层 TCP / IPC 网络通信createServer, connect, Socket构建自定义 TCP 协议服务与客户端
dgramUDP 数据报通信createSocket, send, bind轻量无连接广播或实时数据报传输
readline逐行读取可读流createInterface, on('line')交互式 CLI 输入与逐行日志扫描
repl交互式求值解释器start, context嵌入自定义交互式调试终端
vmV8 隔离上下文脚本执行runInContext, createContext, Script在独立上下文中编译并运行脚本片段(非安全沙箱)
assert运行时断言校验strictEqual, deepStrictEqual, throws(优先严格模式)单元测试与不变式检查
buffer二进制字节缓冲Buffer, alloc, from, concat直接操作原始字节、编码转换与网络封包
console控制台诊断输出log, error, time, timeEnd, Console结构化调试打印与自定义流日志
timers定时器调度接口setTimeout, setInterval, setImmediate, clearTimeout延迟执行、周期轮询与 Promise 化定时器
perf_hooks高精度性能度量performance, PerformanceObserver接口耗时采样与事件循环延迟监控
worker_threads多线程并行计算Worker, isMainThread, parentPort将 CPU 密集型计算卸载到工作线程避免阻塞主循环

运行 Node.js 核心内置模块综合离线实验(fs/path/http/events/os/crypto/zlib/net/vm)

javascript · 阅读源码
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import EventEmitter from 'node:events';
import os from 'node:os';
import url from 'node:url';
import querystring from 'node:querystring';
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import assert from 'node:assert';
import net from 'node:net';
import vm from 'node:vm';
import { performance } from 'node:perf_hooks';
import { isMainThread } from 'node:worker_threads';
import { builtinModules } from 'node:module';

function makeCase(name, expected, actual) {
  return {
    name,
    passed: JSON.stringify(expected) === JSON.stringify(actual),
    expected,
    actual,
  };
}

// Case 1: fs and path built-in modules
async function testFsAndPath() {
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mbsky-bm-'));
  const filePath = path.join(tmpDir, 'output.txt');
  try {
    fs.writeFileSync(filePath, 'Hello Node.js', 'utf8');
    const content = await new Promise((resolve, reject) => {
      fs.readFile(filePath, 'utf8', (err, data) => (err ? reject(err) : resolve(data)));
    });
    const joined = path.posix.join('/home/user/project', 'files', 'example.txt');
    const resolved = path.posix.resolve('/home/user', 'project', './a.js');

    const expected = {
      content: 'Hello Node.js',
      joined: '/home/user/project/files/example.txt',
      resolved: '/home/user/project/a.js',
      dirname: '/home/user/project/files',
      basename: 'example.txt',
      extname: '.html',
    };
    const actual = {
      content,
      joined,
      resolved,
      dirname: path.posix.dirname(joined),
      basename: path.posix.basename(joined),
      extname: path.extname('index.html'),
    };
    return makeCase('fs_and_path_modules', expected, actual);
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 2: http server + events EventEmitter
async function testHttpAndEvents() {
  class MyEmitter extends EventEmitter {}
  const emitter = new MyEmitter();
  const fired = [];
  emitter.on('event', (tag) => fired.push(`on:${tag}`));
  emitter.once('onlyOnce', () => fired.push('once'));
  emitter.emit('event', 'a');
  emitter.emit('onlyOnce');
  emitter.emit('onlyOnce');

  const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello Node.js Server');
  });
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const { port } = server.address();
  try {
    const resp = await fetch(`http://127.0.0.1:${port}/`);
    const body = await resp.text();
    const expected = {
      fired: ['on:a', 'once'],
      httpStatus: 200,
      httpBody: 'Hello Node.js Server',
    };
    const actual = { fired, httpStatus: resp.status, httpBody: body };
    return makeCase('http_and_events_modules', expected, actual);
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

// Case 3: os, url, querystring
function testOsUrlQuerystring() {
  const parsedUrl = new URL('https://example.org:8443/api/items?page=2&tag=node');
  const qsObj = querystring.parse('page=2&tag=node');
  const qsStr = querystring.stringify({ page: '2', tag: 'node' });

  const expected = {
    osPlatformValid: true,
    totalMemPositive: true,
    freeMemPositive: true,
    cpuCountPositive: true,
    tmpdirNonEmpty: true,
    urlHostname: 'example.org',
    urlPathname: '/api/items',
    urlFormatted: 'https://example.org:8443/api/items?page=2&tag=node',
    qsPage: '2',
    qsStr: 'page=2&tag=node',
  };
  const actual = {
    osPlatformValid: typeof os.platform() === 'string' && os.platform().length > 0,
    totalMemPositive: os.totalmem() > 0,
    freeMemPositive: os.freemem() > 0,
    cpuCountPositive: os.cpus().length >= 1,
    tmpdirNonEmpty: typeof os.tmpdir() === 'string' && os.tmpdir().length > 0,
    urlHostname: parsedUrl.hostname,
    urlPathname: parsedUrl.pathname,
    urlFormatted: url.format(parsedUrl),
    qsPage: qsObj.page,
    qsStr,
  };
  return makeCase('os_url_querystring_modules', expected, actual);
}

// Case 4: crypto, zlib, buffer, assert
function testCryptoZlibBufferAssert() {
  const sha256 = crypto.createHash('sha256').update('node-builtin').digest('hex');
  const hmac = crypto.createHmac('sha256', 'secret-key').update('node-builtin').digest('hex');
  const randLen = crypto.randomBytes(16).length;

  const rawBuf = Buffer.concat([Buffer.from('Hello '), Buffer.from('Zlib!')]);
  const compressed = zlib.gzipSync(rawBuf);
  const decompressed = zlib.gunzipSync(compressed).toString('utf8');

  assert.strictEqual(decompressed, 'Hello Zlib!');
  assert.deepStrictEqual({ a: 1 }, { a: 1 });
  let threwAsExpected = false;
  assert.throws(() => {
    threwAsExpected = true;
    throw new Error('boom');
  }, /boom/);

  const expected = {
    sha256Len: 64,
    hmacLen: 64,
    randLen: 16,
    legacyCreateCipherRemoved: true,
    hasCreateCipheriv: true,
    decompressed: 'Hello Zlib!',
    threwAsExpected: true,
  };
  const actual = {
    sha256Len: sha256.length,
    hmacLen: hmac.length,
    randLen,
    legacyCreateCipherRemoved: typeof crypto.createCipher === 'undefined',
    hasCreateCipheriv: typeof crypto.createCipheriv === 'function',
    decompressed,
    threwAsExpected,
  };
  return makeCase('crypto_zlib_buffer_assert', expected, actual);
}

// Case 5: net loopback TCP, vm, perf_hooks, worker_threads, builtinModules catalog
async function testNetVmPerfCatalog() {
  const tcpServer = net.createServer((socket) => {
    socket.on('data', (chunk) => {
      socket.end(`echo:${chunk.toString('utf8')}`);
    });
  });
  await new Promise((resolve) => tcpServer.listen(0, '127.0.0.1', resolve));
  const { port } = tcpServer.address();
  let tcpReply = '';
  try {
    tcpReply = await new Promise((resolve, reject) => {
      const client = net.connect({ host: '127.0.0.1', port }, () => {
        client.write('ping');
      });
      let acc = '';
      client.on('data', (d) => {
        acc += d.toString('utf8');
      });
      client.on('end', () => resolve(acc));
      client.on('error', reject);
    });
  } finally {
    await new Promise((resolve) => tcpServer.close(resolve));
  }

  const ctx = vm.createContext({ x: 10 });
  const vmResult = vm.runInContext('x * 3 + 5', ctx);

  const t0 = performance.now();
  const t1 = performance.now();

  const expectedBuiltins = [
    'fs', 'path', 'http', 'https', 'url', 'querystring', 'os', 'events',
    'stream', 'crypto', 'zlib', 'util', 'child_process', 'cluster', 'dns',
    'domain', 'net', 'dgram', 'readline', 'repl', 'vm', 'assert', 'buffer',
    'console', 'timers', 'perf_hooks', 'worker_threads',
  ];
  const allPresent = expectedBuiltins.every((m) => builtinModules.includes(m));

  const expected = {
    tcpReply: 'echo:ping',
    vmResult: 35,
    perfMonotonic: true,
    isMainThread: true,
    all27BuiltinsPresent: true,
  };
  const actual = {
    tcpReply,
    vmResult,
    perfMonotonic: t1 >= t0,
    isMainThread,
    all27BuiltinsPresent: allPresent,
  };
  return makeCase('net_vm_timers_perf_modules', expected, actual);
}

const cases = [
  await testFsAndPath(),
  await testHttpAndEvents(),
  testOsUrlQuerystring(),
  testCryptoZlibBufferAssert(),
  await testNetVmPerfCatalog(),
];

console.log(JSON.stringify({ version: process.version, cases }));
预期结果 · 待实际运行核验
  • 核对 fs+path 临时读写、http 回环服务与 EventEmitter、os/url/querystring、SHA-256/HMAC/Gzip 与 v24 移除 createCipher 现状、net 回环 TCP 回显、vm 上下文求值及 27 个内置模块目录完整性。
运行 Node.js 核心内置模块综合离线实验(fs/path/http/events/os/crypto/zlib/net/vm)

所需环境:Windows x64、Node.js v24.22.3 本地运行环境。

当前源码 SHA256:5bfa4edb0836cd21f97875cd25b4fc0c08c3351f980d769b6b2183e263e5f009

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Node.js 内置模块实验

所需环境:Windows x64、Node.js v24.22.3 本地运行环境。

ZIP SHA256:b222dbc21a4796245709318d95405beeca1d5bacca0ccd702adece262a4aaf54

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 Node.js v24 中为何推荐写作 import fs from 'node:fs',且表格中提到的 crypto.createCipher 还能继续使用吗?

展开参考解答

加 node: 前缀可明确指向核心内置模块,避免与同名第三方包混淆并兼容仅支持前缀的新模块;crypto.createCipher 因密钥派生不安全已在 Node.js v22+ 移除,须改用带显式随机 IV 的 crypto.createCipheriv。

规范与官方依据