Node Js Child Process Module

02 / May / 2016 by Vikas Bansal 0 comments

Node works efficiently with I/O because of asynchronous event driven programming model,but in case of CPU-intensive tasks it will block the event loop, thus limiting the application responsiveness. CPU-intensive tasks should be performed by different process, to keep event loop free.

So, Node allow us to spawn a new process and assigned the new task to it using child_process module.Another case where you may want to use a child process is ,when you want to simply execute an external command from Node and want the result back once the command finishes.

The child_process module in NodeJs development, provide various method to create and interact with child processes.

  • spawn
  • execFile
  • exec
  1. exec

    the exec method is simplest one to create a child process. when exec() is invoked new shell is launched to execute the command string. The exec() method takes three arguments, first one is the command to execute and second one is an optional configuration object and third is a callback function with three arguments error,stdout,stderr.

    [code lang=”html”]var child_process = require("child_process");
    child_process.exec("ls -la/",{cwd:"/"}, function(err, stdout, stderr) {
    if (err) {
    console.log(err.toString());
    } else if (stdout !== "") {
    console.log(stdout);
    } else {
    console.log(stderr);
    }
    });
    [/code]

  2. execFile

    This method is similar to exec with two differences. First it does not spawn a new shell ,secondly instead of the first argument being the command, here it is the name of the file to execute, with no additional arguments.It takes four arguments first name of file to execute,array for additional arguments, a configuration object and fourth is callback function similar to exec.

    [code lang=”html”]
    var child_process = require("child_process");
    child_process.execFile("ls",[‘-la’],{cwd:"/"} function(err, stdout, stderr) {
    if (err) {
    console.log(err.toString());
    } else if (stdout !== "") {
    console.log(stdout);
    } else {
    console.log(stderr);
    }
    });

    [/code]

  3. spawn

    execFile and exec methods are used to simply execute the command and get the output but spawn is used to provide more complex interaction between child and the parent process. spawn has a number of events and methods to interact with the child process.It take three arguments, the command to be executed without addtional arguments,an array to provide arguments to the command ,and a configuration object. Spawn does not accept a callback function instead it returns a child processs Object.One of important properties of the configuration object is stdio which either accepts an array or one of three strings: ‘ignore’,’pipe’,’inherit’.

    • Pipe – create a pipe between parent and child process.
    • Inherit- inherit the standard streams of parent process eg.process.stdin,process.stdout and process.stderr
    • Ignore- ignore the stream of child process.

    [code lang=”html”]
    var childProcess = require("child_process");
    var child_process = childProcess.spawn("ls", ["-la"], {cwd: "/",stdio: "inherit|pipe|ignore"});

    child_process.stdout.on(‘data’,function(data){
    console.log(data.toString());
    })

    [/code]

    various events emitted by child_process object

    • Error

      This event is emitted when the child cannot be created or killed .

      [code lang=”html”]child_process.on(‘error’,function(err){
      console.log(err.toString());
      });
      [/code]

    • Exit

      This event is emitted when a child process terminates.

      [code lang=”html”]child_process.on(‘exit’,function(exitCode,killSignal){
      console.log(exitCode,killSignal);
      });[/code]

    • Close

      This event is emitted when one of the child process’s standard stream closes.

      [code lang=”html”]
      child_process.on(‘close’,function(exitCode,killSignal){
      console.log(exitCode,killSignal);
      });
      [/code]

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *