fork() method
child_process.fork() is a variant of child_process.spawn() allowing communication between parent and child via send(). It facilitates the isolation of compute-heavy tasks from the main event loop, but numerous child processes can impact performance due to each having its own memory.
Syntax:
child_process.fork(modulePath[, args][, options])
Parameters:
- modulePath: Accepts a string that specifies the module to run in the child.
- args: List of string arguments.
- options: CWD, detached, env, execPath, and execArgv are some of the available options for this method.
Return Value: Returns a ChildProcess instance.
Example: In this example, we will see the use of fork() method.
Javascript
// Write Javascript code here const cp = require( 'child_process' ); let child = cp.fork(__dirname + '/sub.js' ); child.on( 'message' , function (m) { console.log( 'Parent process received:' , m); }); child.send({ hello: 'from parent process' }); child.on( 'close' , (code) => { console.log(`child process exited with code ${code}`); }); |
Javascript
process.on( 'message' , function (m) { console.log( 'Child process received:' , m); }); process.send({ hello: 'from child process' }); |
Output:
Node Child Process
Node is a tool that uses JavaScript and has many useful parts to it. Normally, it does work with one thread at a time, which means it can handle tasks without waiting. However, when there’s a lot of work to be done, we use the child_process module to create additional threads. These extra threads can talk to each other using a built-in messaging system.
The following are the four different ways to create a child process in Nodejs:
Table of Content
- spawn() method
- fork() method
- exec() method
- execFile() method
Above mentioned ways are explained below:
Contact Us