NodeJS Child Processes

Home / NodeJS Child Processes

NodeJS Child Processes

December 9, 2015 | Article | No Comments

Child process is a process created by another process (the parent process). The child inherits most of its parent’s attributes, such as file descriptors.

On Node, we can spawn child processes, which can be another Node process or any process we can launch from the command line. For that we will have to provide the command and arguments to execute it. We can either spawn and live along side with the process (spawn), or we can wait until it exits (exec).

Executing Command

We can launch another process and wait for it to finish like this:

var exec = require('child_process').exec;

exec('cat *.js | wc -l', function(err, stdout, stderr) {
    if (err) {
        console.log('child process exited with error code ' + err.code);
        return;
    }
    console.log(stdout);
});

Here we are executing a command, represented as string like what we type on terminal, as first argument of exec(). Here our command is “cat *.js | wc -l” which has two commands piped. The first command is print out the content of every file which has .js extension. The second argument will retrieve data from the pipe and count the line for each file. The second argument is a callback which will be invoked once the exec has finished.

If the child process returned an error code, the first argument of the callback will contain an instance of Error, with the code property set to the child exit code.

If not, the output of stdout and stderr will be collected and be offered to us as strings.

We can also pass an optional options argument between the command and the callback function:

var options = { timeout: 10000 };
exec('cat *.js | wc -l', options, function (err, stdout, stderr) { ... });

The available options are:

  • encoding: the expected encoding for the child output. Default to ‘utf8’
  • timeout: the timeout in miliseconds for the execution of the command. Default is 0 which does not timeout.
  • maxBuffer: specify the maximum size of the output allowed on stdout or stderr. If exceeded, the child is killed. Default is 200 * 1024
  • killSignal: the signal to be sent to the child, if it times out or exceeds the output buffers. Identified as string.
  • cwd: current working directory, the working directory it will operated in.
  • env: environment variables to be passed in to child process. Defaults to null.

On the killSignal option, we can pass a string identifying the name of the signal we wish to send to the target process. Signals are identified in node as strings.

Spawning Processes

If in previous section we see that we can execute a process. In node we can spawn a new child process based on the child_process.spawn function.

var spawn = require('child_process').spawn;

var child = spawn('tail', ['-f', 'file.txt']);
child.stdout.on('data', function(data) {
    console.log('stdout: ' + data);
});
child.stderr.on('data', function(data) {
    console.log('stderr: ' + data);
});

Here we are spawning a child process to run the “tail” command. The tail command need some arguments, therefore we pass array of string for “tail”, which become second argument of  spawn(). This tail receive arguments “-f” and “file.txt” which will monitor the file “file.txt” if it exists and output every new data appended to it into the stdout.

We also listening to the child stdout and printing it’s output. So here, in this case, we are piping the changes to the “file.txt” file into our Node application.  We also print out the stderr stream.

Killing Process

We can (and should) eventually kill child process by calling the kill method on the child object. Otherwise, it will become zombie process.

var spawn = require('child_process').spawn;

var child = spawn('tail', ['-f', 'file.txt']);
child.stdout.on('data', function(data) {
    console.log('stdout: ' + data);
    child.kill();
});

In UNIX, this sends a SIGTERM signal to the child process.

We can also send another signal to the child process. You need to specify it inside the kill call like this:

child.kill('SIGKILL');

, ,

About Author

about author

xathrya

A man who is obsessed to low level technology.

Leave a Reply

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

Social media & sharing icons powered by UltimatelySocial