Multitasking in Node.js – child process review (2 ed.)
Tags: node
Published: 2021-11-07 18:45:01

![ChildProcess object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ofq222zx986xabv4ua8.png)
 
Image taken from [[by Can Ho on DZone](https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node)] and will be used in this article for educational purpose only !

---

### <u>Let's warm up</u>

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 .

### <u>Process in Node.js</u>

<br>

> **TL;DR** in terms of Node.js V8 VM instance for **.spawn()** vs. **fork()** vs. **worker()**  [[refer to this on my G-Drive docs](https://docs.google.com/document/d/1BOZaJWpJ30n6uLTx9raX_UhR911Rx1v2VRdDiyeThe8/edit?usp=sharing)]

<br>

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](https://medium.com/@MartinMouritzen/how-to-run-php-in-node-js-and-why-you-probably-shouldnt-do-that-fb12abe955b0)] . Operating systems provide access to a great deal of functionality , but much of it is only accessible via the command line only ... <br>

> 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](https://dev.to/meddy672/node-js-processes-os-4jec)] , 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 . <br>

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_)](https://docs.google.com/document/d/1ELZVNsXdqyHGwqRVkjh4_k3OVbEsM48fFP6zXVHMCFw/edit?usp=sharing)

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]

<u>Only one prerequisite</u> : <br>
Must have Python installed on the machine – don't forget to add PATH (Windows) to run from any there (must tick whilst installing) ; 

<br> Now consider such Project-root structure :

```diff
├─Project-root
├───index.js
├───hello-world-again.py
└───package.json, node_modules, etc.
```

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

```python
print("Hello, World from .py!")
```

Now add the following code to your index.js :

```javascript
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
*/
```

<br> 

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 !

---

<u>References</u> : <br>

<sup>[1]</sup>[tutorialspoint.com/process-vs-parent-process-vs-child-process](https://www.tutorialspoint.com/process-vs-parent-process-vs-child-process)

<sup>[2]</sup>[nodejs.org/en/knowledge/child-processes](https://nodejs.org/en/knowledge/child-processes/how-to-spawn-a-child-process/)

<sup>[3]</sup>[digitalocean.com/how-to-launch-child-processes](https://www.digitalocean.com/community/tutorials/how-to-launch-child-processes-in-node-js)

<sup>[4]</sup>[Learning Node by Shelley Powers](https://books.google.lt/books?id=8TRQl6SnDEAC&pg=PA53&lpg=PA53&dq=fork+and+execFile+does+not+work+windows&source=bl&ots=lnLNqTz_Ny&sig=ACfU3U0hN58Ulv_RlbMi2K5BRZoB76EQBg&hl=en&sa=X&ved=2ahUKEwiCvs3ijfDzAhVrk4sKHU9JBc8Q6AF6BAgPEAM#v=onepage&q&f=false)

<sup>[5]</sup>[Child process by K.V. Gaurav](https://medium.com/@gkverma1094/child-process-in-nodejs-b2cd17c76830)

<sup>[6]</sup>[Python in Node.js on G4G](https://www.geeksforgeeks.org/run-python-script-node-js-using-child-process-spawn-method/)

<sup>[7]</sup>[Child Process in Nodejs](https://medium.com/@gkverma1094/child-process-in-nodejs-b2cd17c76830)