Home >>Nodejs Tutorial >Node.js - Scaling Application

Node.js - Scaling Application

Node.js - Scaling Application

Node.js is running in a single-thread mode but it uses an event-driven paradigm to manage competition. It also facilitates the creation of child processes on multi-core CPU based systems to leverage parallel processing.

Infant processes always have three streams child.stdin, child.stdout, and child.stderr that can be shared with parent process stdio streams.

Node provides module child process with the following three main ways to create a child process.

Exec– child_process.exec method runs a shell / console command and buffers the output.
Spawn– child_process.spawn starts a new process with a given command.
Fork− The child_process.fork method is the special spawn() case for creating child processes.

The exec() method

The method child_process.exec executes a command in a shell and buffers the output. It has a signature of –

child_process.exec(command[, options], callback)

Parameter

The definition of the parameters is used here-

Command (String) The command to run with space-separated argument options (Object) may provide one or more of the following options–
cwd (String) Current child process working directory env (Object) Environment key-value pair
encoding (String) (Default: utf8')
Shell (String) Shell in which to execute a command (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, shell in the -c option on UNIX or /s/c on Windows, command line parsing will be compatible with cmd.exe on Windows).
Timeout (Number) (Standard: 0)
maxBuffer (Number) (Default: 200*1024)
killSignal (String) (Default: 'SIGTERM')
uid (Number) Sets the process user identity.
Gid (Number) Sets procedure group identity.
Callback The function gets three error arguments, stdout and stderr that are called with the output when the operation is done

The exec() method returns a fixed size buffer and waits for the cycle to finish and tries to restore all of the buffered data at once.

Example

Creating two javascript files called support.js and master.js –

File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js

const files = require(‘files’);
const child_process = require('child_process');
for(var i=0; i<3; i++) {
var workerProcess = child_process.exec('node support.js '+i,function 
(error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
});
workerProcess.on('exit', function (code) {
console.log(''Exit child process with exit code '+code);
});
}

Output:
Run master.js now to see the result –
$ node master.js

Check the Output. It started server.

Child process exited with exit code 0
stdout: Child Process 1 executed.
stderr:
Child process exited with exit code 0
stdout: Child Process 0 executed.
stderr:
Child process exited with exit code 0
stdout: Child Process 2 executed.

The spawn() Method

child_process.spawn(command[, args][, options])

Parameter

The definition of the parameters is used here-

Command (String) The command to execute
args (Array) List of string arguments
options (Object) that include one or more of the following options –
cwd (String) Current child process work directory.
Env (Object) Pairs key-value setting.
Stdio (Array) String Infant stdio setup.
CustomFds (Array) Deprecated Child file descriptors to be used for stdio.
Detached (Boolean) Child shall be the leader of a process party.
Uid (Number) Sets process user identity.
Gid (Number) Sets procedure group identity.

The spawn() method returns streams (stdout & stderr), which should be used when a volume of data is returned by the process. Spawn() starts receiving the answer as soon as the executing phase begins.

Example

Creating support.js and master.js two javascript files-

File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js

const files = require('files');
const child_process = require('child_process');
for(var i = 0; i<3; i++) {
var workerProcess = child_process.spawn('node', ['support.js', i]);
workerProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
}

Output:
Run master.js now to see the result –
$ node master.js
Verify the Output. Server has started
stdout: Child Process 0 executed.
child process exited with code 0
stdout: Child Process 1 executed.
stdout: Child Process 2 executed.
child process exited with code 0
child process exited with code 0

The fork() Method

Method child process.fork is a special case of spawn() generating Node Processes. It has a signature of –

child_process.fork(modulePath[, args][, options])

Parameters

The definition of the parameters is used here-

ModulePath (String) The child module to run.
Args (Array) List of options in string arguments
Option (Object) can include one or more of the following options –
Cwd (String) Current child process worksheet
Env (Object) Pairs key-value environment.
ExecPath (String) Executable used for child process development.
ExecArgv (Array) List of string arguments passed to the executable (Default: process.execArgv).
Silent (Boolean) If the child's true, stdin, stdout, and stderr are piped to the parent, otherwise they are inherited from the parent, see the spawn() stdio 'stream' and 'inherit' options for more information (default is false).
Uid (Number) Sets process user identity.
Gid (Number) Sets procedure group identity.

In addition to having all the methods in a normal ChildProcess case, the fork method returns an object with an integral communication channel.

Example

Creating support.js and master.js two javascript files-

File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js

const fs = require('fs');
const child_process = require('child_process');
for(var i=0; i<3; i++) {
var worker_process = child_process.fork("support.js", [i]);	
worker_process.on('close', function (code) {
console.log('child process exited with code ' + code);
});
}

Output:
Run master.js now to see the result –
$ node master.js
Check the Output. Server has started.
Child Process 0 executed.
Child Process 1 executed.
Child Process 2 executed.
child process exited with code 0
child process exited with code 0
child process exited with code 0