Node.js「标准库」= node: 内置模块。按模块逐个速查,每个给高频 API 与惯用法。
1. node:fs – 文件系统
描述
三套 API;fs/promises 现代首选;大文件走流。
语法和示例
import { readFile, writeFile, mkdir, rm, stat, readdir } from 'node:fs/promises';
const txt = await readFile('a.txt', 'utf8');
await writeFile('b.txt', data);
await mkdir('x/y', { recursive: true });
await rm('dir', { recursive: true, force: true });
for (const f of await readdir('.')) {}
const info = await stat('a'); // info.size info.mtime2. node:path – 路径
描述
join 拼接/resolve 绝对/extname 扩展名;跨平台必用。
语法和示例
import path from 'node:path';
path.join('a', 'b', 'c.txt');
path.resolve('a'); // 基于 cwd
path.relative(from, to);
path.extname('x.tar.gz'); // '.gz'
path.basename('/a/b/c.txt', '.txt');
path.dirname('/a/b/c.txt');
path.sep; // '/' 或 '\'3. node:http – HTTP 服务与客户端
描述
createServer 事件式;现代请求用全局 fetch。
语法和示例
import http from 'node:http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true }));
});
server.listen(3000);
// req.method / req.url / req.headers;请求端用 fetch4. node:events – EventEmitter
描述
on/once/emit/off;无 error 监听会崩进程。
语法和示例
import { EventEmitter } from 'node:events';
const bus = new EventEmitter();
bus.on('tick', (n) => {});
bus.once('ready', () => {});
bus.emit('tick', 1);
const h = (e) => {}; bus.on('error', h); bus.off('error', h);5. node:stream – 流
描述
五种流;pipeline 自动背压与错误清理;for await 消费。
语法和示例
import { createReadStream } from 'node:fs';
import { pipeline, Transform } from 'node:stream';
import zlib from 'node:zlib';
await pipeline(src, zlib.createGzip(), dst);
const upper = new Transform({
transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); },
});
for await (const chunk of createReadStream('big.log')) {}6. node:crypto – 加密
描述
哈希/随机/密码派生/常量时间比较。
语法和示例
import crypto from 'node:crypto';
crypto.randomUUID();
crypto.randomBytes(16).toString('hex');
crypto.randomInt(1, 101);
crypto.createHash('sha256').update(s).digest('hex');
crypto.scrypt(pw, salt, 64); // 密码哈希
crypto.timingSafeEqual(a, b); // 防时序
crypto.subtle; // WebCrypto7. node:child_process – 子进程
描述
execFile 定长回调;spawn 流式;fork 带 IPC。
语法和示例
import { execFile, spawn, fork } from 'node:child_process';
import { promisify } from 'node:util';
const run = promisify(execFile);
const { stdout } = await run('git', ['status'], { timeout: 30_000 });
const child = spawn('ping', ['-c', '4', host]);
child.stdout.pipe(process.stdout);
fork('./worker.js'); // Node 子进程+IPC8. node:worker_threads – 工作线程
描述
CPU 密集场景;workerData 传入、parentPort 通信。
语法和示例
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
if (isMainThread) {
const w = new Worker(import.meta.filename, { workerData: { n: 1e9 } });
w.on('message', console.log);
} else {
parentPort.postMessage(heavy(workerData.n));
}9. node:url / URLSearchParams
描述
URL 解析构造;query 处理。
语法和示例
import { pathToFileURL } from 'node:url';
const u = new URL('https://a.b/x?page=2#frag');
u.pathname; u.searchParams.get('page'); // '2'
u.searchParams.set('page', '3');
const q = new URLSearchParams({ a: 1, b: '中文' });
q.toString(); // a=1&b=%E4%B8%AD%E6%96%87
pathToFileURL('./local file.txt'); // 空格转 %2010. node:os – 操作系统
描述
cpus/内存/EOL/homedir。
语法和示例
import os from 'node:os';
os.cpus().length; // 核数
os.totalmem(); os.freemem();
os.homedir(); os.tmpdir();
os.EOL; // 平台换行符
os.networkInterfaces();11. node:util – 工具
描述
promisify/inspect/parseArgs/types。
语法和示例
import util from 'node:util';
const sleep = promisify(setTimeout);
util.inspect(obj, { depth: 4, colors: true });
const { values } = util.parseArgs({
options: { n: { type: 'string', short: 'n' } },
});
util.types.isPromise(x);12. node:zlib – 压缩
描述
gzip/deflate/brotli;HTTP 中间件常用。
语法和示例
import zlib from 'node:zlib';
zlib.gzipSync(buf); zlib.gunzipSync(gz);
zlib.brotliCompressSync(buf);
await pipeline(req, zlib.createGzip(), out);13. node:readline – 行读取
描述
逐行处理命令行与大文件问答。
语法和示例
import readline from 'node:readline/promises';
import { stdin, stdout } from 'node:process';
const rl = readline.createInterface({ input: stdin, output: stdout });
const name = await rl.question('名字? ');
rl.close();
// 处理流:
import { createInterface } from 'node:readline';
for await (const line of createInterface({ input: stream })) {}14. node:timers/promises – Promise 定时器
描述
sleep/setInterval 的异步迭代器。
语法和示例
import { setTimeout as sleep, setInterval } from 'node:timers/promises';
await sleep(1000);
for await (const tick of setInterval(500)) {
if (cond()) break; // 可 break 的定时循环
}15. node:test – 内置测试器
描述
test/describe/it + assert/strict;18+ 内置。
语法和示例
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
describe('api', () => {
test('add', () => assert.equal(1 + 1, 2));
test('async', async () => {
assert.deepEqual(await f(), { a: 1 });
});
});
// 跑:node --test