Updated April 3, 2023
Introduction to Node.js Child Process
The core of node.js is a JavaScript which is client side. JavaScript gives us environment to run on server side which is known as node.js. The main part is js is as we all know that js is single threaded. So without any doubt we can say node.js is also single threaded. But we can’t reply on single thread on complex real time application at this time we use Node.js child processes.
How Node.js Child Process works?
To help to execute many tasks at a time node.js has module called node.js child process. With the help of these processes we can release as many small processes as we require. Node.js child process has one main process. Node.js process has some arguments.
Run following code on your local machine:
Code
console.log(process.argv);
You will get the the actual files and path of the node where it exactly on your machine.
Code
console.log(process.argv)
[ 'C:\\Program Files\\nodejs\\node.exe' ]
undefined
Output
How to Create Node.js Child Process using various ways?
Here we have four different types of child processes.
- fork()
- exec()
- execFile()
- spawn()
Given below are the four ways to create different processes in the node.js:
1. fork()
This function is the same as the spawn. This function makes the use of modulo=e called eventEmmiter. As we all know eventEmmiter is a node.js module to propagate the events. Suppose we have two files. File1 and File2.
File1:
Code
const { fork } = require('child_process');
const message= fork('file2.js');
message.on('message', (msg) => {
console.log('Which fruits are in stock', msg);
});
message.send({ 'There are bananas': ' fav' });
File2:
Code
process.on('message', (msg) => {
console.log('Message from parent:', msg);
});
let n= 0;
setInterval(() => {
process.send({ n: n++ });
},
2000);
Output
2. exec()
Now the second one is exec() function. This function is to make use of the shell to execute the command. This function makes the use of the shell. This function buffers the output.
This function has some commands and parameters to set as a requirement.
Command (String): We need to set the command. Followed by different options.
There are several options as follows:
- cwd (String): This shows the location of the child process in the Current working directory.
- shell (String): This helps to execute with the shell option on windows or another respective os.
- timeout (Number): We set here the timeout. By default, it set to zero(0).
- uid (Number): This is to set the user identity of the process.
- env (Object): This is to know environment key-value pairs.
- encoding (String): This is to set encoding for the program. By default, it set to the UTF8.
- gid (Number): This is to set the group identity of the process.
- killSignal (String): If we want to stop propogation then we will use this option. The default value for this is ‘SIGTERM’.
- maxBuffer (Number): With this, we can set the buffer count. By default is 200*1024.
Syntax
child_process.exec(command[, options], callback function)
Example: execfun.js
console.log("The Child Process is " + process.argv[2] + " getting implemented" );
Example: execfun1.js
We need to include a file system module here.
Code
const fileSystem = require('fs');
const process1 = require('child_process');
for(var i=0; i<3; i++) {
var process2 = process1 .exec('node execfun.js'+i,function
(err, stdout, stderr) {
if (err) {
console.log(err.stack);
console.log('The error message: '+err.code);
console.log(' the Signal message: '+err.signal);
}
console.log('the output for stdout: ' + stdout);
console.log('the output for stderr: ' + stderr);
});
process2.on('on exit', function (code) {
console.log('The child process is getting end here. '+code);
});
}
Output
If we run the execfun2.js then we will get the following output.
3. execFile()
Sometimes we need to run our file without the use of the shell. Shell is risky to use. It comes with some security threats. This function works similarly to the exec function. The use of execFile function is smoother than exec() function.
4. spawn()
spawn means to release a new child process out of it. The same thing applies to this function also. Span function makes the use of od EventEmmiter. The spawn process returns the stream of stdout and stderr. Every function has some parameters to be get executed.
Command
- args (Array): This has the Array elements.
Options:
As we have seen in the syntax following are the different options we can make use of.
- cwd (String): This shows the current working directory in which the current process is running.
- stdio (Array): This shows the Child’s stdio configuration.
- env (Object): This gives us the environment key-value pairs.
- customFds (Array): This is the deprecated File. This is used for the child to use of stdio.
- uid (Number): This is to set the user identity of the process.
- gid (Number): This is to set the group identity of the process.
- detached (Boolean): This is the child who will be a process group leader.
Syntax
const { spawn } = require('child_process');
Every time we use the function to make use of the process we need to first destructor it from child_proocess as shown above.
Example: spwan1.js
console.log("The Spawn child process " + process.argv[2] + " implemented");
Example: spawn2.js
Code
const fileSystem = require('fs');
const spawnProcess = require('child_process');
for(var i=0; i<3; i++) {
var process2 = spawnProcess.spawn('node', ['spawn1.js', i]);
process2.stdout.on('data', function (dataValue) {
console.log('The output for stdout: ' + dataValue);
});
process2.stderr.on('data', function (dataValue) {
console.log(' The output for stderr: ' + dataValue);
});
process2.on('close', function (spawnCode) {
console.log('The spawn child process has code ' + spawnCode);
});
}
To see the result please run the following command.
Code
node spawn2.js
And then hit enter, you will see below output:
Output
Conclusion
There are several functions for the child process. But the above mentioned four are mainly used. These child processes help us to implement actual node programming which is made for. Each process can work as a separate node.
Recommended Articles
This is a guide to Node.js Child Process. Here we discuss the Introduction, how Node.js child process works? and how to create Node.js child process using various ways? You may also have a look at the following articles to learn more –