How to do it…

Since the code of the previous section used .spawn() to launch a new Node instance and run some code, it's fairly obvious that we can quickly and simply adjust it to use .fork() instead. Also, we won't have to use stdin and stdout to communicate, opting for messaging instead.

First, let's start with the parent code. It would become the following; the key differences are the usage of .fork() instead of .spawn(), and the way that the file path is sent to the child process:

// Source file: src/process_fork.js

const path = require("path");
const { fork } = require("child_process");

const child = fork(path.resolve("out/process_fork_dir.js"));

child.send({ path: "/home/fkereki" });

child.on("message", data => {
console.log(String(data));
});

Then, the child code would also show small variations, in the way messages are received, and data is sent to the parent:

// Source file: src/process_fork_dir.js

const fs = require("fs");

process.on("message", obj => {
// Received a path to process
fs
.readdirSync(obj.path)
.sort((a, b) => a.localeCompare(b, [], { sensitivity: "base" }))
.filter(file => !file.startsWith("."))
.forEach(file => process.send && process.send(file));
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset