如何生成子进程并与 Deno 通信?

How to spawn child process and communicate with it Deno?

假设我有 2 个脚本,father.ts 和 child.ts,我如何从 father.ts 生成 child.ts 并定期从 father.ts 发送消息到 child.ts ?

您必须使用 Worker API

father.ts

const worker = new Worker("./child.ts", { type: "module", deno: true });
worker.postMessage({ filename: "./log.txt" });

child.ts

self.onmessage = async (e) => {
  const { filename } = e.data;
  const text = await Deno.readTextFile(filename);
  console.log(text);
  self.close();
};

您可以使用 .postMessage

发送消息

您可以使用子进程。这是一个例子:proc with PushIterable

这将使您可以异步地从 non-Deno 个子进程以及 Deno 子进程发送和接收多个命令。

小心,因为这需要 --allow-run 才能工作,如果您关心的话,这几乎总是会突破沙箱。