How to do it…

Using .spawn() is similar to .exec() in general terms. Let's now use a separate process to read a directory and send its results back. We will be passing the path we want to process using a stream, and we'll get the list of found files also through streaming.

To start, let's have the main code, which will spawn a process:

// Source file: src/process_spawn.js

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

const child = spawn("node", [path.resolve("out/process_spawn_dir.js")]);

child.stdin.write("/home/fkereki");

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

child.stdout.on("end", () => {
child.kill();
});

To finish, we need the child process, which would be as follows:

// Source file: src/process_spawn.js

const fs = require("fs");

process.stdin.resume();

process.stdin.on("data", path => {
// Received a path to process
fs
.readdirSync(path)
.sort((a, b) => a.localeCompare(b, [], { sensitivity: "base" }))
.filter(file => !file.startsWith("."))
.forEach(file => process.stdout.write(file + " "));

process.stdout.end();
});
..................Content has been hidden....................

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