第 04 章:内置核心模块全集
大约 5 分钟
第 04 章:内置核心模块全集
Node.js 自带的内置标准模块涵盖了从文件操作、流处理、网络通信到加解密与性能优化的全套能力。熟练运用核心模块是高效率开发的基石。
1. 文件系统 (fs) 与路径处理 (path)
1.1 path.join vs path.resolve 经典坑点
path.join(...paths):仅仅将多个路径片段拼接在一起,规范化成一个相对或绝对路径。path.resolve(...paths):从右向左解析路径,直到拼出一个绝对路径。如果还没解析完,就会以process.cwd()作为前缀补齐。
const path = require('node:path');
// 假设 process.cwd() 为 /Users/project
console.log(path.join('/a', 'b', '../c'));
// 输出: /a/c
console.log(path.resolve('a', 'b'));
// 输出: /Users/project/a/b (因为 'a' 是相对路径,自动拼上了 cwd)
console.log(path.resolve('/a', 'b'));
// 输出: /a/b (/a 是根绝对路径,不再往左拼)1.2 fs.promises 与大文件流式读写
小文件可以使用 fs.readFile / fs.writeFile 一次性载入内存;但对于 GB 级别的大文件,直接载入会导致 OOM (内存溢出),必须使用流 (Stream)。
const fs = require('node:fs');
const { pipeline } = require('node:stream/promises');
const zlib = require('node:zlib');
// ✅ 管道化大文件复制与压缩(无爆内存风险)
async function compressFile(srcPath, destPath) {
try {
await pipeline(
fs.createReadStream(srcPath),
zlib.createGzip(),
fs.createWriteStream(destPath)
);
console.log('文件压缩并写入完成!');
} catch (err) {
console.error('处理过程发生错误:', err);
}
}2. 数据流 (Stream)、二进制 (Buffer) 与事件 (Events)
2.1 堆外内存 Buffer 机制
Buffer 是 Node.js 用来在内存中直接操作二进制字节流的类,分配在 V8 堆外内存中:
// 推荐使用 Buffer.alloc 或 Buffer.from,弃用 Buffer() 构造函数
const buf1 = Buffer.alloc(10); // 分配 10 字节,全填 0
const buf2 = Buffer.from('Node.js 架构', 'utf-8');
console.log(buf2); // <Buffer 4e 6f 64 65 2e 6a 73 20 e6 9e b6 e6 9e 84>
console.log(buf2.toString('utf-8')); // Node.js 架构2.2 流的核心概念与背压控制 (Backpressure)
当读取流的速度大于写入流的承载能力时,未写入的数据会被临时缓存在内存的 Buffer 队列中。如果不加限制,队列暴涨就会挤爆内存。这就是背压 (Backpressure)。
pipeline 和 .pipe() 内部自动实现了背压机制:当写入流的水位线 (highWaterMark) 满时,自动暂停读取流 (pause);当缓冲排空后,再恢复读取 (resume)。
const { Readable } = require('node:stream');
// 自定义可读流
class CounterStream extends Readable {
constructor(maxCount = 5) {
super();
this.count = 0;
this.maxCount = maxCount;
}
_read() {
this.count++;
if (this.count <= this.maxCount) {
this.push(`Data Chunk #${this.count}\n`);
} else {
this.push(null); // EOF 信号
}
}
}2.3 EventEmitter 与防内存泄漏
EventEmitter 是 Node.js 事件驱动的核心实现:
const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();
// 避免 MaxListenersExceededWarning 告警(默认上限为 10)
myEmitter.setMaxListeners(20);
// 单次监听
myEmitter.once('init', () => console.log('初始化配置一次'));
// 销毁时务必及时解绑监听,防止闭包引起的内存泄漏
function onData(chunk) {
console.log('接收到数据:', chunk);
}
myEmitter.on('data', onData);
// 清理: myEmitter.off('data', onData);2.4 StringDecoder 解码多字节字符防截断
当将二进制 Buffer 分块转为字符串时,UTF-8 中文(占 3 字节)可能刚好被切在字节中间,直接 .toString() 会产生乱码。StringDecoder 能缓存多出的不完整字节,拼接下一个 chunk 完美解码:
const { StringDecoder } = require('node:string_decoder');
const decoder = new StringDecoder('utf-8');
const buf = Buffer.from('中国'); // 6 字节
const chunk1 = buf.subarray(0, 4); // 包含了完整的 "中" (3字节) 和 "国" 的第1个字节
const chunk2 = buf.subarray(4); // "国" 的剩余2字节
console.log(chunk1.toString('utf-8')); // 中 (产生了无损乱码)
console.log(decoder.write(chunk1)); // 中 (自动保留末尾incomplete字节)
console.log(decoder.write(chunk2)); // 国 (完美解码)3. 网络通信与传输 (http, net, dns)
3.1 手写原生 HTTP 服务与 Agent 连接池
const http = require('node:http');
// 1. 创建 HTTP 服务
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/api/data') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', received: JSON.parse(body) }));
});
} else {
res.writeHead(404).end('Not Found');
}
});
server.listen(3000, () => console.log('Server running at http://localhost:3000'));3.2 TCP 原生通信与粘包/拆包处理
TCP 是面向字节流的协议,没有消息边界,连续发送的包可能会在接收端粘连 (粘包) 或被截断 (拆包)。通常使用 “固定 Header + Body 长度” 协议解决:
const net = require('node:net');
// TCP 服务端
const server = net.createServer(socket => {
socket.on('data', buffer => {
// 假设前 4 字节为 Header (记录 Body 长度)
if (buffer.length >= 4) {
const bodyLen = buffer.readUInt32BE(0);
const body = buffer.subarray(4, 4 + bodyLen).toString('utf-8');
console.log('解析出有效 Body:', body);
}
});
});
server.listen(8080);3.3 dns.lookup vs dns.resolve 区别
| 特性 | dns.lookup(hostname, callback) | dns.resolve(hostname, rrtype, cb) |
|---|---|---|
| 底层实现 | 调用 C 库的 getaddrinfo | 直接使用 C-Ares 库发起 DNS 网络数据包查询 |
| 执行位置 | 占用 Libuv 线程池 | 不占用 线程池,在 Event Loop 中异步执行 |
| 读取配置 | 尊重本地 /etc/hosts 文件 | 绕过本地 /etc/hosts,只查 DNS 服务器 |
4. 实用工具与性能测量 (crypto, zlib, perf_hooks)
4.1 加密与哈希 (crypto)
const crypto = require('node:crypto');
// 1. 计算哈希值
const hash = crypto.createHash('sha256').update('mySecretString').digest('hex');
// 2. AES-256-GCM 对称加密 (推荐安全算法)
function encrypt(text, secretKey) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', secretKey, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
return { encrypted, iv: iv.toString('hex'), authTag };
}4.2 高精度性能测量 (perf_hooks)
在测量后端接口或复杂算法耗时时,Date.now() 精确度不够且受系统时钟校准影响,应当使用 perf_hooks:
const { performance, PerformanceObserver } = require('node:perf_hooks');
const obs = new PerformanceObserver((items) => {
const entry = items.getEntries()[0];
console.log(`[性能测量] ${entry.name}: ${entry.duration.toFixed(3)} ms`);
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('start-calc');
// 执行耗时逻辑
for(let i = 0; i < 1000000; i++) {}
performance.mark('end-calc');
performance.measure('百万循环耗时', 'start-calc', 'end-calc');