1. child_process 内置 IPC 通道
使用 fork() 创建子进程时,父子进程之间会建立一条专用 IPC 通道,通过 process.send() / process.on('message') 收发消息,传输的是 JSON 序列化数据。
// parent.js
const { fork } = require('child_process');
const child = fork('child.js');
child.send({ hello: 'world' });
child.on('message', msg => console.log('from child:', msg));
// child.js
process.on('message', msg => {
console.log('from parent:', msg);
process.send({ received: true });
});
适用场景:父子进程一对一通信,简单任务分发。
2. 管道(pipe / stdio)
通过标准输入输出流(stdin/stdout/stderr)传递数据,适合流式处理。
const { spawn } = require('child_process');
const child = spawn('grep', ['hello']);
child.stdout.on('data', data => console.log(data.toString()));
child.stdin.write('hello world\n');
child.stdin.end();
适用场景:与外部程序协作、流式数据处理(如 shell pipeline)。
3. 共享内存(SharedArrayBuffer + Worker Threads)
worker_threads 模块支持通过 SharedArrayBuffer 在线程间共享内存,配合 Atomics 实现同步,性能极高。
const { Worker, isMainThread, workerData } = require('worker_threads');
const shared = new SharedArrayBuffer(4);
const arr = new Int32Array(shared);
if (isMainThread) {
new Worker(__filename, { workerData: shared });
Atomics.store(arr, 0, 42);
} else {
console.log(Atomics.load(new Int32Array(workerData), 0)); // 42
}
适用场景:CPU 密集型任务、高频数据共享(注意线程安全)。
4. Unix Domain Socket / Named Pipe
通过本机 socket 文件进行通信,速度接近共享内存,支持双向通信,也适合不同语言的进程互通。
// server
const net = require('net');
net.createServer(sock => {
sock.on('data', d => sock.write('pong: ' + d));
}).listen('/tmp/app.sock');
// client
const client = net.connect('/tmp/app.sock');
client.write('ping');
client.on('data', d => console.log(d.toString()));
适用场景:同机多进程通信、与非 Node 进程互通。
5. TCP / HTTP / WebSocket
走网络协议的通信方式,天然支持跨机器,是微服务架构的基础。
// 用 HTTP 做简单 IPC
const http = require('http');
http.createServer((req, res) => res.end('pong')).listen(3001);
http.get('http://localhost:3001', res => {
res.on('data', d => console.log(d.toString()));
});
适用场景:分布式系统、微服务、需要跨机通信。
6. 消息队列(Redis / RabbitMQ / Kafka 等)
借助外部消息中间件实现解耦的异步通信,支持发布/订阅、持久化、重试等能力。
// 使用 ioredis 的 Pub/Sub
const Redis = require('ioredis');
const pub = new Redis(), sub = new Redis();
sub.subscribe('channel');
sub.on('message', (ch, msg) => console.log(msg));
pub.publish('channel', 'hello');
适用场景:高并发、解耦、需要消息持久化或跨服务广播。
对比总结
| 方式 | 速度 | 跨机器 | 复杂度 | 适用场景 |
|---|---|---|---|---|
| IPC 通道 (fork) | 快 | ❌ | 低 | 父子进程 |
| 管道 (pipe) | 快 | ❌ | 低 | 流式数据 |
| SharedArrayBuffer | 最快 | ❌ | 高 | 线程间共享 |
| Unix Socket | 很快 | ❌ | 中 | 同机多进程 |
| TCP/HTTP | 中 | ✅ | 中 | 微服务 |
| 消息队列 | 中 | ✅ | 高 | 分布式解耦 |
选择时优先考虑:是否跨机 → 是否需要解耦 → 对延迟的要求。