How to spawn child process and communicate with it Deno?
Asked Answered
D

2

7

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 ?

Didier answered 29/5, 2020 at 12:6 Comment(0)
H
8

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

Hyohyoid answered 29/5, 2020 at 12:9 Comment(7)
But child process in node allows you to run terminal commands. Seems like the does notInhabitancy
You can use Deno.run if you want to spawn shell commands.Hyohyoid
#61711287 see my answer thereHyohyoid
Very helpful, thank you. Am I able to send multiple commands and receive multiple responses for the same running process in Deno? I'm having a hard time finding examples.Inhabitancy
In one of my examples I show how to write to stdin. You need to read from stdout and write to stdin.Hyohyoid
why is it called 'worker'?Pretend
Because Deno tries to implement Web APIs when it makes sense, they didn't create the name developer.mozilla.org/en-US/docs/Web/API/Worker/WorkerHyohyoid
M
0

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.

Mclaughlin answered 16/2, 2022 at 4:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.