Join us in unraveling the intricacies of Node.js as an extensible application platform in this Mytour article.
Node.js - Extending Possibilities
Node.js operates in a single-thread mode, yet it utilizes an event-driven programming model for concurrent processing, enabling the creation of child processes to facilitate parallel execution on multi-core CPU systems.
Child processes have three streams: child.stdin, child.stdout, and child.stderr, which can be shared with the stdio stream of the parent process.
The exec() method in Node.js allows for the execution of shell commands, providing a way to interact with the underlying operating system.
Node offers the child_process module below to create child processes:
- exec: The child_process.exec method runs a command in the shell/console and returns the output as a buffer.
- spawn: The child_process.spawn method initiates a new process with the given command.
- fork: The child_process.fork method is a special case of spawn() to create child processes.
2. The exec() Method in Node.js
The child_process.exec method executes a command in the shell and returns the output as a buffer. It utilizes the signature below:
child_process.exec(command[, options], callback)
Where:
- command (string) represents the command to run, with parameters separated by spaces.
- options (object) may include one or more of the following options:
+ cwd (string): the current working directory of the child process.
+ env (object): key-value pairs for the environment.
+ terminationSignal (string) (default: 'SIGTERM').
+ userIdentifier (number): sets the user identity of the process.
+ groupIdentifier (number): sets the group identity of the process.
- Callback: This function will receive 3 arguments: error, stdout, and stderr, these arguments are called with the output when the process ends.
The exec() method returns a buffer with maximum size and waits for the process to finish, attempting to return all buffer data at once.
Example:
Create 2 JavaScript files named support.js and master.js:
File: support.js:
Display a message using console.log('Child Process ' + process.argv[2] + ' executed.' );
Master File:
Import the fs module: const fs = require('fs');
Import the child_process module: const child_process = require('child_process');
Loop through and execute the following block of code three times:
Define a workerProcess to execute 'node support.js ' followed by the current value of i:
This function takes three arguments: error, stdout, and stderr:
If an error occurs within the function block:
Display the stack trace of the error:
Display the error code:
Display the signal received:
End of the error handling block.
Display the standard output:
Display the standard error:
End of the function block.
When the worker process exits, execute the following block of code with the exit code:
Display a message indicating the child process exited with a specific exit code:
End of the event listener block.
End of the function block.
Next, run the master.js file to see the result:
Execute the master.js file using Node.js.
Confirm the output, indicating that the server has started.
The child process exited with exit code 0.
Standard output: Child Process 1 executed.
Standard error:
The child process exited with exit code 0.
Standard output: Child Process 0 executed.
Standard error:
The child process exited with exit code 0.
Standard output: Child Process 2 executed.
3. The spawn() Method in Node.js
The child_process.spawn method launches a new process with the given command, using the following signature:
child_process.spawn(command[, args][, options])
In which:
- Command (string) represents the command to execute.
- args (array): a list of string arguments.
- options (object) can include one or more of the following options:
+ cwd (string): the current working directory of the child process.
+ env (object): key-value pairs representing the environment.
+ stdio (array) string configuration of the Child's stdio.
+ customFds (array): files not allowed for the child to use for stdio.
+ detached (Boolean): child will lead the process.
+ uid (number): sets the user identity of the process.
+ gid (number): sets the group identity of the process.
The spawn() method returns streams (stdout & stderr) and is used when the process returns a data block. spawn() begins receiving responses immediately after the process starts executing.
Example:
Create 2 JavaScript files named support.js and master.js:
File: support.js:
Display a message indicating the execution of the child process:
File: master.js:
Import the child_process module: const child_process = require('child_process');
Loop through and execute the following block of code three times:
Define a workerProcess to spawn a Node.js process with arguments from the support.js file:
Listen for stdout data from the workerProcess:
Display the stdout data:
End of the event listener block.
Listen for stderr data from the workerProcess:
Display the stderr data:
End of the event listener block.
When the worker process closes, execute the following block of code with the exit code:
Display a message indicating the child process exited with a specific code:
End of the event listener block.
End of the function block.
Next, run master.js to see the result:
Run the command node master.js
Confirm the output and server startup:
Standard output: Child Process 0 executed.
Child process exited with code 0
Standard output: Child Process 1 executed.
Standard output: Child Process 2 executed.
Child process exited with code 0
Child process exited with code 0
4. The fork() Method in Node.js
The child_process.fork method is a special case of spawn() to create Node processes, using the following signature:
child_process.fork(modulePath[, args][, options])
In which:
- modulePath (string): Specifies the module to run in the child.
- args (array): List of string arguments.
- options (object) can include one or more of the following options:
+ cwd (string): current working directory of the child process.
+ env (object): Environment key-value pairs.
+ execPath (string): Used to create the child process.
+ execArgv (array): List of string arguments assigned to the executing file (default: process.execArgv).
+ silent (Boolean): If true, the child's stdin, stdout, and stderr will be sent to the parent process, otherwise it will be inherited from the parent process.
+ uid (number): sets the user identity of the process.
+ gid (number): sets the group identity of the process.
The fork method returns an object with a communication channel integrated into all methods of the standard ChildProcess variant.
Example:
Create two JavaScript files named support.js and master.js:
File: support.js:
console.log('Child Process ' + process.argv[2] + ' executed.' );
File: master.js:
Import the fs module: const fs = require('fs');
Import the child_process module: const child_process = require('child_process');
Loop through a block of code three times:
Create a worker process using the fork method: var worker_process = child_process.fork('support.js', [i]);
When the worker process closes, execute the following block of code with the exit code: worker_process.on('close', function (code) {
Display a message indicating the child process exited with a specific code: console.log('child process exited with code ' + code);
End of the event listener block.
End of the function block.
Proceed to run master.js to view the results:
Run the command: node master.js
Confirm the output and server startup:
Child Process 0 executed.
Execution of Child Process 1 completed.
Execution of Child Process 2 completed.
Child process terminated with exit code 0.
Child process terminated with exit code 0.
Child process exited with status code 0.
This article by Mytour introduces you to Node.js - An Extensible Application. If you have any inquiries or questions, please feel free to leave your comments below the article. Additionally, readers can explore other articles on Mytour to learn more about the Express Framework in Node.js.
