Bun

指南进程

使用 Bun 启动子进程并使用 IPC 进行通信

使用 Bun.spawn() 来启动子进程。在启动第二个 bun 进程时,您可以在两个进程之间打开一个直接的进程间通信 (IPC) 通道。

注意 — 此 API 仅与 其他 bun 进程兼容。使用 process.execPath 获取当前运行的 bun 可执行文件的路径。

parent.ts
const child = Bun.spawn(["bun", "child.ts"], {
  ipc(message) {
    /**
     * The message received from the sub process
     **/
  },
});

父进程可以使用返回的 Subprocess 实例上的 .send() 方法将消息发送到子进程。发送的子进程的引用在 ipc 处理程序中也作为第二个参数提供。

parent.ts
const childProc = Bun.spawn(["bun", "child.ts"], {
  ipc(message, childProc) {
    /**
     * The message received from the sub process
     **/
    childProc.send("Respond to child")
  },
});

childProc.send("I am your father"); // The parent can send messages to the child as well

同时,子进程可以使用 process.send() 将消息发送到其父进程,并使用 process.on("message") 接收消息。这与 Node.js 中用于 child_process.fork() 的 API 相同。

child.ts
process.send("Hello from child as string");
process.send({ message: "Hello from child as object" });

process.on("message", (message) => {
  // print message from parent
  console.log(message);
});

所有消息都使用 JSC serialize API 进行序列化,该 API 支持与 postMessagestructuredClone 支持的 可传输类型相同的类型,包括字符串、类型化数组、流和对象。

child.ts
// send a string
process.send("Hello from child as string");

// send an object
process.send({ message: "Hello from child as object" });

有关完整文档,请参阅 文档 > API > 子进程