Web Programming TutorialsLearn about the Scaling Application in Nodejs

Learn about the Scaling Application in Nodejs

In this article, we are going to discuss how to scale Node.js applications. It may be surprising but true that the Node.js operates in a single-thread mode where concurrency is handled by an event-driven paradigm. It can leverage parallel processing on a system with multi-core CPU by the creation of child processes. Such child processes deal with the three main streams known as child.stdin, child.stdout, and child.stderr. These streams are shared with the stdio streams of the respective parent processes.

The Node.js provides a child_process module to create a child process and there are three main ways to create a child process as follows.

• The child_process.exec – is a method that operates a command in a shell or console and buffers the output.
• The child_process.spawn – is a method that introduces a new process with a given command.
• The child_process.fork − is a method that creates the child processes.

The child_process.exec () method in Node.js
As explained above, the child_process.exec is a method that operates a command in a shell or console and buffers the output. It returns a maximum size buffer and waits for the process to get terminated in order to return all the buffered data altogether. It has the following syntax.

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

Parameters
The following are the parameters description.

• Command: This is the actual command to execute which is of String type.
• Options: This is an Object that may include one or more of the options as follows.

S No

Options

Description

1.

Option cwd

This is a String type. It represents the current working directory of the child process.

2.

Option env

This is a Object type. It represents environment key-value pairs.

3.

Option encoding

This is a String type. It has the default value as ‘utf8’.

4.

Option shell

This is a String type. It is used to execute the command that has default ‘/bin/sh’ on UNIX, and ‘cmd.exe’ on Windows. Also, it should understand the -c switch on UNIX or /s /c on Windows operating system. The command line parsing should be compatible with cmd.exe on Windows platform.

5.

Option timeout

This is aNumber type. It has the default value as 0.

6.

Option maxBuffer

This is a Number type. It has the default value as 200*1024.

7.

Option killSignal

This is aString type. It has the default value as ‘SIGTERM’.

8.

Option uid

This is a Number type. It is used to set the user identity of the process.

9.

Option gid

This is aThis is a Number type. It is used to set the group identity of the process.

• Callback: It is the actual function which accepts three arguments. They are error, stdout, and stderr. They are called post process termination with the output.

Example on the child_process.exec () method in Node.js
The following is an example on the child_process.exec () method in Node.js. Here, we have created the MasterProcess.js as shown below, where we are going to execute Node.js application PathModule.js
MasterProcess.js

var fs = require('fs');
var child_processing = require('child_process');

   var workerProcessing = child_processing.exec('node PathModule.js '+1,function 
      (error, stdout, stderr) {
      
      if (error) {
         console.log(error.stack);
         console.log('Error code during child process: '+error.code);
         console.log('Signal received during child process: '+error.signal);
      }
      console.log('The output stdout: ' + stdout);
      console.log('The error stderr: ' + stderr);
   });

   workerProcessing.on('exit', function (code) {
      console.log('Child process has terminated with the exit code as '+code);
   });

Output
When we execute the above code, then we will observe the following output.

Child process has terminated with the exit code as 0
The output stdout: Path normalization is : \trail\trail1\doublehash\hash
joint path is : \trail\trail1\doublehash\hash

The error stderr:

The child_process.spawn () method in Node.js
As explained above, the child_process.spawn is a method that introduces a new process with a given command. It returns streams (i.e. stdout and stderr). It is usually used when the process returns a large amount of data. It receives the response as soon as the process begins implementation. It has the following syntax.

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

Parameters
The following are the parameters description.

• Command: It is the actual command to execute which is of type String.
• Args: It is the list of arguments as Array type.
• Options: It is an Object that may include one or more of the options as follows.

S No

1.

Option cwd

This is a String type. It represents the current working directory of the child process.

2.

Option env

This is a Object type. It represents environment key-value pairs.

3.

Option stdio

This is an Array String type. It represents child’s stdio configuration.

4.

Option customFds

This is an Array type. It represents the deprecated file descriptors for the child to use for stdio.

5.

Option detached

This is a Boolean type. It indicates whether the child will be a process group leader or not.

8.

Option uid

This is a Number type. It is used to set the user identity of the process.

9.

Option gid

This is a Number type. It is used to set the group identity of the process.

Example on the child_process.spawn () method in Node.js

SpawnProcess.js

var fs = require('fs');
var child_processing = require('child_process');

for(var i = 0; i<3; i++) {
	   var workerProcessing = child_processing.spawn('node', ['PathModule.js', i]);

	   workerProcessing.stdout.on('data', function (data) {
	      console.log('The output stdout: ' + data);
	   });

	   workerProcessing.stderr.on('data', function (data) {
	      console.log('The error stderr: ' + data);
	   });

	   workerProcessing.on('close', function (code) {
	      console.log('The child process terminated with the code as ' + code);
	   });
	}

Output
When we execute the above code, then we will observe the following output.

The output stdout: Path normalization is : \trail\trail1\doublehash\hash

The output stdout: joint path is : \trail\trail1\doublehash\hash

The output stdout: Path normalization is : \trail\trail1\doublehash\hash

The output stdout: joint path is : \trail\trail1\doublehash\hash

The child process terminated with the code as 0
The child process terminated with the code as 0
The output stdout: Path normalization is : \trail\trail1\doublehash\hash

The output stdout: joint path is : \trail\trail1\doublehash\hash

The child process terminated with the code as 0

The child_process.fork () method in Node.js
As explained above, the child_process.fork is a method that creates the child processes. It returns streams (i.e. stdout and stderr). It returns an object that has a built-in communication channel along with all the methods in a regular ChildProcess instance. It has the following syntax.

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

Parameters
The following are the parameters description.

• ModulePath: This is a type String. It represents a module path to operate in the child.
• Args: This is This is athe list of arguments as Array type.
• Options: This is an Object that may include one or more of the options as follows.

S No

1.

Option cwd

This is a String type. It represents the current working directory of the child process.

2.

Option env

This is aObject type. It represents environment key-value pairs.

3.

Option execPath

This is a String type. It represents a path which is used to create the child process.

4.

Option execArgv

IThis is an Array type. It represents a list of string arguments which are passed to the executable. The default value is process.execArgv.

5.

Option silent

This is a Boolean type. If it is true then the stdin, stdout, and stderr of the child will be automatically piped to the parent. If it is false, then it will inherit them from the parent. The default value is false.

8.

Option uid

This is aNumber type. It is used to set the user identity of the process.

9.

Option gid

This is a Number type. It is used to set the group identity of the process.

Example on the child_process.fork () method in Node.js
The following is an example on the child_process.fork () method in Node.js. Here, we have created ForkProcess.js as shown below where we are going to execute Node.js application PathModule.js

ForkProcess.js

var fs = require('fs');
var child_processing = require('child_process');
 
   var worker_processing = child_processing.fork("PathModule.js", [1]);	

   worker_processing.on('close', function (code) {
      console.log('The child process has terminated with the code as ' + code);
   });

Output
When we execute the above code, we will observe the following output.

Path normalization is : \trail\trail1\doublehash\hash
joint path is : \trail\trail1\doublehash\hash
The child process has terminated with the code as 0

Source code for this article

Conclusion: –
In this article, we discussed scaling Node.js applications by using child_process module of Node.js.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -