Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spawn child process and communicate with it Deno?

Tags:

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 ?

like image 629
Wong Jia Hau Avatar asked May 29 '20 12:05

Wong Jia Hau


People also ask

How do you spawn a child process?

Spawned Child Processes. The spawn function launches a command in a new process and we can use it to pass that command any arguments. For example, here's code to spawn a new process that will execute the pwd command. const { spawn } = require('child_process'); const child = spawn('pwd');

What is the output in the child process?

The read end of one pipe serves as standard input for the child process, and the write end of the other pipe is the standard output for the child process.


1 Answers

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

like image 147
Marcos Casagrande Avatar answered Oct 11 '22 07:10

Marcos Casagrande