DEV Community

Lukas Gaucas
Lukas Gaucas

Posted on • Updated on

Multitasking in Node.js – child process review (2 ed.)

ChildProcess object

Image taken from [by Can Ho on DZone] and will be used in this article for educational purpose only !


Let's warm up

With reference to the cover image above , calling each of methods will return a Child process object instance originated from Child process class that implements EventEmitter , consequently such stream based object instance can directly register .on event listeners as it inherits EventEmitter from Child process class (module) . Now as we got warm , let's jump straight away into the subject of this article .

Process in Node.js

TL;DR in terms of Node.js V8 VM instance for .spawn() vs. fork() vs. worker() [refer to this on my G-Drive docs]

A parent process may have multiple child process*es* but a child process only one parent process [1] . If you want Node.js process start another program for you, then look no further than the child_process module [2] : aside from dealing with long-running tasks , this module can also interface with the OS and run shell commands [3] . In layman's terms it allows us to run more than JavaScript , as it might be Git , Python , PHP or any other programming language , in case of PHP in Node.js child process as up for & against [read this] . Operating systems provide access to a great deal of functionality , but much of it is only accessible via the command line only ...

It would be nice to be able to access this functionality from a Node application . That’s where child processes come into place .


In the main (a.k.a. parent) process the stdin is readable stream (input) & the pair of stdout & stderr is writable stream (output) – all in one recognized as stdio [Matt Eddy on Dev.to] , whilst in child process(es) is completely opposite i.e. child process‘s stdin is also an input , but consumed as subsequent writable stream , where as the pair of stdout & stderr is an output, but yielded as readable stream . **Worth to mention, stdin, stdout & stderr are part of POSIX terminology .


Node.js allows us to run a system command within a child process and listen in on its input/output (I/O) . This enable us developers to pass arguments to the command , and even pipe the results of one command to another [4] . In terms of piping , it's about connecting two and mores streams into one chain : it can be either readable or writable stream but not both , since pipe(/-ing) is by definition unidirectional [5] , not bi-directional (a.k.a. duplex) . Be aware : child processes implements utilization of pipes internally , of course the method of pipe() could be used explicitly as well .

It's time to examine Child process factors used in Node.js , so we could move further (link below) :

Child process factors (G-Drive shareable – read only)

As we got acknowledged with Child process factors , let's get a bit into Python itself which source code we will run as Node.js sub-process . We all know Python is good in machine learning algorithms, deep learning algorithms and many features provided that is lack in Node.js , fortunately – thanks to child processes – it can be exploited into Node JS application as well without a sweat (not covered in this article currently) . Let's examine the following child process introductory example [made upon 6 & 7 – see for References list below]

Only one prerequisite :

Must have Python installed on the machine – don't forget to add PATH (Windows) to run from any there (must tick whilst installing) ;


Now consider such Project-root structure :

├─Project-root
├───index.js
├───hello-world-again.py
└───package.json, node_modules, etc.
Enter fullscreen mode Exit fullscreen mode

Within hello-world-again.py add some Python-related source code such as :

print("Hello, World from .py!")
Enter fullscreen mode Exit fullscreen mode

Now add the following code to your index.js :

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

let child_process_1 = spawn('python', ["./hello_world_again.py"])

child_process_1.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
});
child_process_1.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
});
child_process_1.on("close", (code) => {
console.log(`child process exited with code ${code}`);
});

// Expected output : 
/*
stdout: Hello, World from .py!

child process exited with code 0
*/
Enter fullscreen mode Exit fullscreen mode

That's all for now . If any typos found and (or) suggestions could be made, please leave it in the comment section below . Thank you and see you in the next one !


References :

[1]tutorialspoint.com/process-vs-parent-process-vs-child-process

[2]nodejs.org/en/knowledge/child-processes

[3]digitalocean.com/how-to-launch-child-processes

[4]Learning Node by Shelley Powers

[5]Child process by K.V. Gaurav

[6]Python in Node.js on G4G

[7]Child Process in Nodejs

Discussion (0)