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:
varspawn=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('childprocessexitedwith
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access