node-ipc
用于 nodejs 进程间的通信,很多工具底层都有用到它
两个本地进程间的通信
使用 node-ipc 可以非常容易进行本地的进程通信,可以是不相关的 nodejs 进程,也可以是父子进程,举个例子:
import { spawn } from 'node:child_process'
import ipc from 'node-ipc'
import os from 'os'
import path from 'path'
ipc.config.id = 'server';
ipc.config.retry = 1500;
ipc.config.silent = true
ipc.serve(
path.resolve(os.tmpdir(), `app.rockets`), // 指定路径
function(){
ipc.server.on('message', function(data, socket){
console.log('server reciver', data)
ipc.server.emit(socket, 'message', 'world')
});
});
ipc.server.start();
const child = spawn('tsx', ['./child.ts'], {
stdio: ['pipe', 'inherit' ,'pipe'],
});import ipc from 'node-ipc'
import os from 'os'
import path from 'path'
ipc.config.id = 'client';
ipc.config.retry=1500;
ipc.config.silent = true
ipc.connectTo(
'rockets', // 指定 client id
path.resolve(os.tmpdir(), `app.rockets`), // 指定路径
function(){
ipc.of.rockets.on('message', function(data){
console.log('client reciver', data)
});
ipc.of.rockets.emit('message', 'hello');
});$ tsx server.ts
server reciver hello
client reciver world可以看到,需要由一个进程作为 server 调用 ipc.serve, 另一个进程作为 client 进行 ipc.connect 连接
所以其实可以存在多个 client ,连接同一个 server,而 server 可以对任意一个 client 发送消息,只需要传入对应 client 的 socket 即可
广播
例如,向所有的 client 发送 message 事件,并携带数据
ipc.server.broadcast('message', 'world')