使用 Bun.spawn()
衍生子程序。當衍生第二個 bun
程序時,您可以在兩個程序之間開啟直接的行程間通訊 (IPC) 管道。
注意 — 此 API 僅與其他 bun
程序相容。使用 process.execPath
取得目前執行中 bun
執行檔的路徑。
const child = Bun.spawn(["bun", "child.ts"], {
ipc(message) {
/**
* The message received from the sub process
**/
},
});
父程序可以使用傳回的 Subprocess
實例上的 .send()
方法,將訊息傳送至子程序。發送子程序的參考也可以在 ipc
處理器中作為第二個參數使用。
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 相同。
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 序列化,這允許與 postMessage
和 structuredClone
相同的可傳輸類型集合,包括字串、類型化陣列、串流和物件。
// send a string
process.send("Hello from child as string");
// send an object
process.send({ message: "Hello from child as object" });
請參閱文件 > API > 子程序以取得完整文件。