Chapter 8. Child Processes

Operating systems provide access to a great deal of functionality, but much of it is only accessible via the command line. It would be nice to be able to access this functionality from a Node application. That’s where child processes come in.

Node allows us to run a system command within a child process and listen in on its input/output. This includes being able to pass arguments to the command, and even pipe the results of one command to another. The next several sections explore this functionality in more detail.

Warning

All but the last examples demonstrated in this chapter use Unix commands. They work on a Linux system and should also work in OS X. They won’t, however, work in a Windows Command window.

child_process.spawn

There are four different techniques you can use to create a child process. The most common one is using the spawn method. This technique launches a command in a new process, passing in any arguments. Pipes are established between the parent application and the child process for stdin, stdout, and stderr.

In the following, we create a child process to call the Unix pwd command to print the current directory. The command takes no arguments:

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

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

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

pwd.on('close', function (code) {
  console.log('child process exited 

Get Learning Node, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.