5 Node provides a tri-directional `popen(3)` facility through the
6 `child_process` module.
8 It is possible to stream data through a child's `stdin`, `stdout`, and
9 `stderr` in a fully non-blocking way.
11 To create a child process use `require('child_process').spawn()` or
12 `require('child_process').fork()`. The semantics of each are slightly
13 different, and explained below.
15 ## Class: ChildProcess
17 `ChildProcess` is an `EventEmitter`.
19 Child processes always have three streams associated with them. `child.stdin`,
20 `child.stdout`, and `child.stderr`. These may be shared with the stdio
21 streams of the parent process, or they may be separate stream objects
22 which can be piped to and from.
24 The ChildProcess class is not intended to be used directly. Use the
25 `spawn()` or `fork()` methods to create a Child Process instance.
29 * `code` {Number} the exit code, if it exited normally.
30 * `signal` {String} the signal passed to kill the child process, if it
31 was killed by the parent.
33 This event is emitted after the child process ends. If the process terminated
34 normally, `code` is the final exit code of the process, otherwise `null`. If
35 the process terminated due to receipt of a signal, `signal` is the string name
36 of the signal, otherwise `null`.
44 A `Writable Stream` that represents the child process's `stdin`.
45 Closing this stream via `end()` often causes the child process to terminate.
47 If the child stdio streams are shared with the parent, then this will
54 A `Readable Stream` that represents the child process's `stdout`.
56 If the child stdio streams are shared with the parent, then this will
63 A `Readable Stream` that represents the child process's `stderr`.
65 If the child stdio streams are shared with the parent, then this will
72 The PID of the child process.
76 var spawn = require('child_process').spawn,
77 grep = spawn('grep', ['ssh']);
79 console.log('Spawned child pid: ' + grep.pid);
82 ### child.kill([signal])
86 Send a signal to the child process. If no argument is given, the process will
87 be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
89 var spawn = require('child_process').spawn,
90 grep = spawn('grep', ['ssh']);
92 grep.on('exit', function (code, signal) {
93 console.log('child process terminated due to receipt of signal '+signal);
96 // send SIGHUP to process
99 Note that while the function is called `kill`, the signal delivered to the child
100 process may not actually kill it. `kill` really just sends a signal to a process.
104 ### child.send(message, [sendHandle])
107 * `sendHandle` {Handle object}
109 Send a message (and, optionally, a handle object) to a child process.
111 See `child_process.fork()` for details.
113 ## child_process.spawn(command, [args], [options])
115 * `command` {String} The command to run
116 * `args` {Array} List of string arguments
118 * `cwd` {String} Current working directory of the child process
119 * `customFds` {Array} **Deprecated** File descriptors for the child to use
120 for stdio. (See below)
121 * `env` {Object} Environment key-value pairs
123 * return: {ChildProcess object}
125 Launches a new process with the given `command`, with command line arguments in `args`.
126 If omitted, `args` defaults to an empty Array.
128 The third argument is used to specify additional options, which defaults to:
134 `cwd` allows you to specify the working directory from which the process is spawned.
135 Use `env` to specify environment variables that will be visible to the new process.
137 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
139 var util = require('util'),
140 spawn = require('child_process').spawn,
141 ls = spawn('ls', ['-lh', '/usr']);
143 ls.stdout.on('data', function (data) {
144 console.log('stdout: ' + data);
147 ls.stderr.on('data', function (data) {
148 console.log('stderr: ' + data);
151 ls.on('exit', function (code) {
152 console.log('child process exited with code ' + code);
156 Example: A very elaborate way to run 'ps ax | grep ssh'
158 var util = require('util'),
159 spawn = require('child_process').spawn,
160 ps = spawn('ps', ['ax']),
161 grep = spawn('grep', ['ssh']);
163 ps.stdout.on('data', function (data) {
164 grep.stdin.write(data);
167 ps.stderr.on('data', function (data) {
168 console.log('ps stderr: ' + data);
171 ps.on('exit', function (code) {
173 console.log('ps process exited with code ' + code);
178 grep.stdout.on('data', function (data) {
182 grep.stderr.on('data', function (data) {
183 console.log('grep stderr: ' + data);
186 grep.on('exit', function (code) {
188 console.log('grep process exited with code ' + code);
193 Example of checking for failed exec:
195 var spawn = require('child_process').spawn,
196 child = spawn('bad_command');
198 child.stderr.setEncoding('utf8');
199 child.stderr.on('data', function (data) {
200 if (/^execvp\(\)/.test(data)) {
201 console.log('Failed to start child process.');
205 Note that if spawn receives an empty options object, it will result in
206 spawning the process with an empty environment rather than using
207 `process.env`. This due to backwards compatibility issues with a deprecated
210 There is a deprecated option called `customFds` which allows one to specify
211 specific file descriptors for the stdio of the child process. This API was
212 not portable to all platforms and therefore removed.
213 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
214 stderr]` to existing streams; `-1` meant that a new stream should be created.
215 Use at your own risk.
217 There are several internal options. In particular `stdinStream`,
218 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
219 undocumented APIs in Node, they should not be used.
221 See also: `child_process.exec()` and `child_process.fork()`
223 ## child_process.exec(command, [options], callback)
225 * `command` {String} The command to run, with space-separated arguments
227 * `cwd` {String} Current working directory of the child process
228 * `customFds` {Array} **Deprecated** File descriptors for the child to use
229 for stdio. (See below)
230 * `env` {Object} Environment key-value pairs
232 * `encoding` {String} (Default: 'utf8')
233 * `timeout` {Number} (Default: 0)
234 * `maxBuffer` {Number} (Default: 200*1024)
235 * `killSignal` {String} (Default: 'SIGTERM')
236 * `callback` {Function} called with the output when process terminates
240 * Return: ChildProcess object
242 Runs a command in a shell and buffers the output.
244 var util = require('util'),
245 exec = require('child_process').exec,
248 child = exec('cat *.js bad_file | wc -l',
249 function (error, stdout, stderr) {
250 console.log('stdout: ' + stdout);
251 console.log('stderr: ' + stderr);
252 if (error !== null) {
253 console.log('exec error: ' + error);
257 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
258 will be `null`. On error, `error` will be an instance of `Error` and `err.code`
259 will be the exit code of the child process, and `err.signal` will be set to the
260 signal that terminated the process.
262 There is a second optional argument to specify several options. The
268 killSignal: 'SIGTERM',
272 If `timeout` is greater than 0, then it will kill the child process
273 if it runs longer than `timeout` milliseconds. The child process is killed with
274 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
275 amount of data allowed on stdout or stderr - if this value is exceeded then
276 the child process is killed.
279 ## child_process.execFile(file, args, options, callback)
281 * `file` {String} The filename of the program to run
282 * `args` {Array} List of string arguments
284 * `cwd` {String} Current working directory of the child process
285 * `customFds` {Array} **Deprecated** File descriptors for the child to use
286 for stdio. (See below)
287 * `env` {Object} Environment key-value pairs
289 * `encoding` {String} (Default: 'utf8')
290 * `timeout` {Number} (Default: 0)
291 * `maxBuffer` {Number} (Default: 200*1024)
292 * `killSignal` {String} (Default: 'SIGTERM')
293 * `callback` {Function} called with the output when process terminates
297 * Return: ChildProcess object
299 This is similar to `child_process.exec()` except it does not execute a
300 subshell but rather the specified file directly. This makes it slightly
301 leaner than `child_process.exec`. It has the same options.
304 ## child_process.fork(modulePath, [args], [options])
306 * `modulePath` {String} The module to run in the child
307 * `args` {Array} List of string arguments
309 * `cwd` {String} Current working directory of the child process
310 * `customFds` {Array} **Deprecated** File descriptors for the child to use
311 for stdio. (See below)
312 * `env` {Object} Environment key-value pairs
314 * `encoding` {String} (Default: 'utf8')
315 * `timeout` {Number} (Default: 0)
316 * Return: ChildProcess object
318 This is a special case of the `spawn()` functionality for spawning Node
319 processes. In addition to having all the methods in a normal ChildProcess
320 instance, the returned object has a communication channel built-in. The
321 channel is written to with `child.send(message, [sendHandle])` and messages
322 are received by a `'message'` event on the child.
326 var cp = require('child_process');
328 var n = cp.fork(__dirname + '/sub.js');
330 n.on('message', function(m) {
331 console.log('PARENT got message:', m);
334 n.send({ hello: 'world' });
336 And then the child script, `'sub.js'` might look like this:
338 process.on('message', function(m) {
339 console.log('CHILD got message:', m);
342 process.send({ foo: 'bar' });
344 In the child the `process` object will have a `send()` method, and `process`
345 will emit objects each time it receives a message on its channel.
347 By default the spawned Node process will have the stdin, stdout, stderr
348 associated with the parent's.
350 These child Nodes are still whole new instances of V8. Assume at least 30ms
351 startup and 10mb memory for each new Node. That is, you cannot create many
354 The `sendHandle` option to `child.send()` is for sending a handle object to
355 another process. Child will receive the handle as as second argument to the
356 `message` event. Here is an example of sending a handle:
358 var server = require('net').createServer();
359 var child = require('child_process').fork(__dirname + '/child.js');
360 // Open up the server object and send the handle.
361 server.listen(1337, function() {
362 child.send({ server: true }, server._handle);
365 Here is an example of receiving the server handle and sharing it between
368 process.on('message', function(m, serverHandle) {
370 var server = require('net').createServer();
371 server.listen(serverHandle);