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 > 子程序