Wong Jia Hau
Wong Jia Hau

Reputation: 3069

How to spawn child process and communicate with it Deno?

Suppose I have 2 script, father.ts and child.ts, how do I spawn child.ts from father.ts and periodically send message from father.ts to child.ts ?

Upvotes: 7

Views: 2264

Answers (2)

j50n
j50n

Reputation: 1

You can use child processes. Here is an example: proc with PushIterable

This will let you send and receive multiple commands from non-Deno child processes asynchronously, as well as Deno child processes.

Be careful as this requires --allow-run to work, and this almost always breaks out of the sandbox, if you care about that.

Upvotes: 0

Marcos Casagrande
Marcos Casagrande

Reputation: 40414

You have to use the 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();
};

You can send messages using .postMessage

Upvotes: 8

Related Questions