Node.js Child Processes are a way to create new processes in a Node.js application. These processes can be used to perform tasks in parallel or execute external commands, scripts or programs, and communicate with the parent process through the use of inter-process communication mechanisms.
In Simpler Terms :
When you run a Node.js application, it runs in a single process. It is utilizing only a single core of the CPU
This means that if your application is doing a lot of work, it might take a long time to finish. Node.js Child Processes allow you to create additional processes in your application. Each process can run a different task, which means that your application can do multiple things at the same time on all available cores of the CPU to speed up the process.
For example, imagine you are running a web server in Node.js that needs to perform some CPU-intensive calculations like processing graphics, mathematical calculations, and video or image compression.
By using Child Processes, you can spawn(give birth) multiple processes to do those calculations in parallel, which means that your server can continue to respond to incoming requests while the calculations are being done.
So! What are these Child processes:
Node.js provides three types of Child Processes:
spawn()
child_process.spawn()
: This function launches a new process with a given command and set of arguments. The spawned process runs independently of the parent process.NodeJS provides a package called
child_process
with utilities for spawning processes.const { spawn } = require('child_process'); const pythonProcess = spawn('python', ['myscript.py', 'arg1']);
This above code will spawn a new process that runs the
python
command with the argumentmyscript.py
and the argumentarg1
.The
spawn()
method returns a ChildProcess object(returned to variablepythonProcess
above), which has properties and methods that can be used to interact with the spawned process.For example, you can listen to events like
data
,error
, andexit
to get the output of the spawned process and handle errors.Here's an example of how to listen for the
data
event to get the output of the spawned process:pythonProcess.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); pythonProcess.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); pythonProcess.on('exit', (code) => { console.log(`child process exited with code ${code}`); });
In this example, we're listening for the
data
event on thestdout
andstderr
streams of the ChildProcess object
fork()
child_process.fork()
: This method is similar tochild_process.spawn()
, the difference is that it creates only a new Node.js process.So, in the below code, we pass a javascript file child.js to the ChildProcess Object "fork".
const { fork } = require('child_process'); const childProcess = fork('./child.js'); childProcess.on('message', message => { console.log(`Received message from child process: ${message}`); }); childProcess.send('Hello from parent process!'); process.on('message', message => { console.log(`Received message from parent process: ${message}`); }); process.send('Hello from child process!');
In the above example, we have a parent process (
parent.js
) that creates a new child process usingchild_process.fork()
and sends a message to it usingchildProcess.send()
.The child process (
child.js
) listens for messages from the parent process usingprocess.on('message')
and sends a message back usingprocess.send()
.
exec()
child_process.exec()
: This is a method in Node.js that allows you to run a shell command or script from within your Node.js program.like for example :
const { exec } = require('child_process'); // Execute a shell command -> ls -la exec('ls -la', (error, stdout, stderr) => { if (error) { console.error(`Error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); });
In the above example,
-> we first import the
exec
function from thechild_process
module.-> We then call
exec
and pass in the command we want to execute (ls -la
, - which lists the contents of the current directory).-> We also pass in a callback function that will be called when the command finishes executing. It returns the stdout, stderr, and the exit code of the command as a callback.
The callback function takes three arguments:
error
,stdout
, andstderr
. If an error occurred,error
will be set to the error object. Otherwise,stdout
will contain the standard output of the command, andstderr
will contain the standard error output.You could replace the 'ls -la' command with any other shell command or script that you want to run from your Node.js program.
Usage of the Child Processes
Each type of Child Process has its own advantages and is suitable for specific use cases.
Node.js Child Processes can be used in various real-life scenarios to improve the performance and functionality of applications. Here are some examples:
Image and video processing:- When working with images or videos in a Node.js application, Child Processes can be used to perform CPU-intensive tasks like resizing, cropping, or encoding. By using multiple Child Processes, the application can process multiple files simultaneously, which reduces the overall processing time.
Web scraping:- Web scraping requires fetching data from multiple web pages, which can be time-consuming. Child Processes can be used to fetch data from multiple web pages in parallel, making the scraping process faster.
Server-side rendering:- Server-side rendering involves generating HTML on the server-side, which can take a lot of time for complex applications. Child Processes can be used to generate HTML in parallel, which speeds up the rendering process.
Machine learning:- Node.js can be used for machine learning applications, and Child Processes can be used to perform the heavy computations required by machine learning algorithms. By using multiple Child Processes, the computations can be performed in parallel, which reduces the overall training time.
In summary, Node.js Child Processes can be used in any application that requires parallel processing of CPU-intensive tasks, making the application faster and more efficient.