We now have a youtube channel. Subscribe!

Node.js | Scaling Application

Node.js | Scaling Application


Hello folks! welcome back to a new edition of our tutorial on Node.js. In this section of our tutorial on Node.js, we will be studying about Scaling Application in Node.js.

Node.js runs in a single-threaded mode, but it utilizes an event-driven model for handling concurrency. It also speeds creation of child processes to leverage parallel processing on multi-core CPU based systems.

Child processes always have three streams child.stdin, child.stdout, and then child.stderr which may be shared with the stdio streams of the parent process.

Node provides child_process module which has the following three main ways to create a child process -

  • exec - child_process.exec method runs a command in a shell/console and buffers the result.
  • spawn - child_process.spawn method launches a new process with a given command.
  • fork - The child_process.fork method is a special case of spawn() method for creating child processes.


The exec() Method

child_process.exec method runs a command in shell/console and buffers the result.

Syntax

child_process.exec method has the syntax below -

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

Parameter Details

Below is the description of the parameters used -

  • command (String) - The command to run, with space-separated arguments.
  • options (Object) - May be made up of one or more of the following options -
    • cwd (String) - Current working directory of the child process
    • env (Object) - Environment key-value pair
    • encoding (String) - Default: 'utf8'.
    • shell (String) - Shell to execute command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows OS, the shell should understand the -c switch on UNIX or /s /c on Windows OS. On Windows OS, command line parsing should be compatible with cmd.exe)
    • timeout (Number) - (Default: 0)
    • maxBuffer (Number) - (Default: 200*1024)
    • killSignal (String) - (Default: 'SIGTERM')
    • uid (Number) - It sets the user identify of the process
    • gid (Number) - It sets the group identify of the process
  • callback - Gets three arguments error, stdout and stderr which are called with the output when process terminates.

Return Value

This method return a buffer with a max size and waits for the process to end and tries to return all the buffered data at once.

Example

Let us create two js files named support.js and master.js -

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 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('Child process exited with exit code '+code);
   });
}

Now, run the master.js to see the result -

$ node master.js

Output

Verify the result.

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

The child_process.spawn method launches a new process with a new command.

Syntax

child_process.spawn method has the below syntax -

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

Parameter Details

Below is the description of the parameters used -

  • command (String) - The command to run.
  • args (Array) - List of string arguments.
  • options (Object) - May be made up of one or more of the following options -
    • cwd (String) - Current working directory of the child process
    • env (Object) - Environment key-value pairs
    • stdio (Array) - The string Child's stdio configuration
    • customFds (Array) - Deprecated file descriptors for the child to use for stdio
    • detached (Boolean) - The child will be a process group leader
    • uid (Number) - It sets the user identify of the process
    • gid (Number) - It sets the group identify of the process

Return Value

This method returns streams and it should be used when the process returns a volume amount of data. The spawn() method starts receiving the response soon as the process starts executing.

Example

Let us create two js files named support.js and master.js -

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 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);
   });
}

Now run the master.js to see the result -

$ node master.js

Output

Verify the result.

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

The child_process.fork method is a special case of spawn() to create Node processes.

Syntax

child_process.fork method has the syntax below -

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

Parameter Details

Below is the description of the parameters used -

  • modulePath (String) - The module to run in the child.
  • args (Array) - List of string arguments.
  • options (Object) - May be made up of one or more of the following items -
    • cwd (String) - Current working directory of the child process
    • env (Object) - Environment key-value pairs
    • execPath (String) - Executable used to create the child process
    • execArgv (Array) - A list of the string arguments passed to the executable (Default: process.execArgv)
    • silent (Boolean) - If true, stdin, stdout and stderr of the child will be piped to the parent, else they will be inherited from the parent, see the 'pipe' and 'inherit' options for spawn()'s stdio for more info (the default value is false)
    • uid (Number) - It sets the user identity of the process
    • gid (Number) - It sets the group identity of the process.

Return Value

The child_process.fork() method returns the object with built-in communication channel in addition to having all methods in a normal childProcess instance.

Example

Let us create two js files named support.js and master.js -

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);
   });
}

Now run the master.js to see the result -

$ node master.js

Output

Verify the result.

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


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about Node.js Packaging.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain