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 序列化,這允許使用與 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 > 子程序 以取得完整的說明文件。