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`.
38 Note that the child process stdio streams might still be open.
44 This event is emitted when the stdio streams of a child process have all
45 terminated. This is distinct from 'exit', since multiple processes
46 might share the same stdio streams.
48 ### Event: 'disconnect'
50 This event is emitted after using the `.disconnect()` method in the parent or
51 in the child. After disconnecting it is no longer possible to send messages.
52 An alternative way to check if you can send messages is to see if the
53 `child.connected` property is `true`.
57 * `message` {Object} a parsed JSON object or primitive value
58 * `sendHandle` {Handle object} a Socket or Server object
60 Messages send by `.send(message, [sendHandle])` are obtained using the
67 A `Writable Stream` that represents the child process's `stdin`.
68 Closing this stream via `end()` often causes the child process to terminate.
70 If the child stdio streams are shared with the parent, then this will
77 A `Readable Stream` that represents the child process's `stdout`.
79 If the child stdio streams are shared with the parent, then this will
86 A `Readable Stream` that represents the child process's `stderr`.
88 If the child stdio streams are shared with the parent, then this will
95 The PID of the child process.
99 var spawn = require('child_process').spawn,
100 grep = spawn('grep', ['ssh']);
102 console.log('Spawned child pid: ' + grep.pid);
105 ### child.kill([signal])
109 Send a signal to the child process. If no argument is given, the process will
110 be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
112 var spawn = require('child_process').spawn,
113 grep = spawn('grep', ['ssh']);
115 grep.on('exit', function (code, signal) {
116 console.log('child process terminated due to receipt of signal '+signal);
119 // send SIGHUP to process
122 Note that while the function is called `kill`, the signal delivered to the child
123 process may not actually kill it. `kill` really just sends a signal to a process.
127 ### child.send(message, [sendHandle])
130 * `sendHandle` {Handle object}
132 When using `child_process.fork()` you can write to the child using
133 `child.send(message, [sendHandle])` and messages are received by
134 a `'message'` event on the child.
138 var cp = require('child_process');
140 var n = cp.fork(__dirname + '/sub.js');
142 n.on('message', function(m) {
143 console.log('PARENT got message:', m);
146 n.send({ hello: 'world' });
148 And then the child script, `'sub.js'` might look like this:
150 process.on('message', function(m) {
151 console.log('CHILD got message:', m);
154 process.send({ foo: 'bar' });
156 In the child the `process` object will have a `send()` method, and `process`
157 will emit objects each time it receives a message on its channel.
159 There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
160 containing a `NODE_` prefix in its `cmd` property will not be emitted in
161 the `message` event, since they are internal messages used by node core.
162 Messages containing the prefix are emitted in the `internalMessage` event, you
163 should by all means avoid using this feature, it is subject to change without notice.
165 The `sendHandle` option to `child.send()` is for sending a TCP server or
166 socket object to another process. The child will receive the object as its
167 second argument to the `message` event.
169 **send server object**
171 Here is an example of sending a server:
173 var child = require('child_process').fork('child.js');
175 // Open up the server object and send the handle.
176 var server = require('net').createServer();
177 server.on('connection', function (socket) {
178 socket.end('handled by parent');
180 server.listen(1337, function() {
181 child.send('server', server);
184 And the child would the recive the server object as:
186 process.on('message', function(m, server) {
187 if (m === 'server') {
188 server.on('connection', function (socket) {
189 socket.end('handled by child');
194 Note that the server is now shared between the parent and child, this means
195 that some connections will be handled by the parent and some by the child.
197 **send socket object**
199 Here is an example of sending a socket. It will spawn two childs and handle
200 connections with the remote address `74.125.127.100` as VIP by sending the
201 socket to a "special" child process. Other sockets will go to a "normal" process.
203 var normal = require('child_process').fork('child.js', ['normal']);
204 var special = require('child_process').fork('child.js', ['special']);
206 // Open up the server and send sockets to child
207 var server = require('net').createServer();
208 server.on('connection', function (socket) {
211 if (socket.remoteAddress === '74.125.127.100') {
212 special.send('socket', socket);
215 // just the usual dudes
216 normal.send('socket', socket);
220 The `child.js` could look like this:
222 process.on('message', function(m, socket) {
223 if (m === 'socket') {
224 socket.end('You where handled as a ' + process.argv[2] + ' person');
228 Note that once a single socket has been sent to a child the parent can no
229 longer keep track of when the socket is destroyed. To indicate this condition
230 the `.connections` property becomes `null`.
231 It is also recomended not to use `.maxConnections` in this condition.
233 ### child.disconnect()
235 To close the IPC connection between parent and child use the
236 `child.disconnect()` method. This allows the child to exit gracefully since
237 there is no IPC channel keeping it alive. When calling this method the
238 `disconnect` event will be emitted in both parent and child, and the
239 `connected` flag will be set to `false`. Please note that you can also call
240 `process.disconnect()` in the child process.
242 ## child_process.spawn(command, [args], [options])
244 * `command` {String} The command to run
245 * `args` {Array} List of string arguments
247 * `cwd` {String} Current working directory of the child process
248 * `stdio` {Array|String} Child's stdio configuration. (See below)
249 * `customFds` {Array} **Deprecated** File descriptors for the child to use
250 for stdio. (See below)
251 * `env` {Object} Environment key-value pairs
253 * return: {ChildProcess object}
255 Launches a new process with the given `command`, with command line arguments in `args`.
256 If omitted, `args` defaults to an empty Array.
258 The third argument is used to specify additional options, which defaults to:
264 `cwd` allows you to specify the working directory from which the process is spawned.
265 Use `env` to specify environment variables that will be visible to the new process.
267 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
269 var util = require('util'),
270 spawn = require('child_process').spawn,
271 ls = spawn('ls', ['-lh', '/usr']);
273 ls.stdout.on('data', function (data) {
274 console.log('stdout: ' + data);
277 ls.stderr.on('data', function (data) {
278 console.log('stderr: ' + data);
281 ls.on('exit', function (code) {
282 console.log('child process exited with code ' + code);
286 Example: A very elaborate way to run 'ps ax | grep ssh'
288 var util = require('util'),
289 spawn = require('child_process').spawn,
290 ps = spawn('ps', ['ax']),
291 grep = spawn('grep', ['ssh']);
293 ps.stdout.on('data', function (data) {
294 grep.stdin.write(data);
297 ps.stderr.on('data', function (data) {
298 console.log('ps stderr: ' + data);
301 ps.on('exit', function (code) {
303 console.log('ps process exited with code ' + code);
308 grep.stdout.on('data', function (data) {
312 grep.stderr.on('data', function (data) {
313 console.log('grep stderr: ' + data);
316 grep.on('exit', function (code) {
318 console.log('grep process exited with code ' + code);
323 Example of checking for failed exec:
325 var spawn = require('child_process').spawn,
326 child = spawn('bad_command');
328 child.stderr.setEncoding('utf8');
329 child.stderr.on('data', function (data) {
330 if (/^execvp\(\)/.test(data)) {
331 console.log('Failed to start child process.');
335 Note that if spawn receives an empty options object, it will result in
336 spawning the process with an empty environment rather than using
337 `process.env`. This due to backwards compatibility issues with a deprecated
340 The 'stdio' option to `child_process.spawn()` is an array where each
341 index corresponds to a fd in the child. The value is one of the following:
343 1. `'pipe'` - Create a pipe between the child process and the parent process.
344 The parent end of the pipe is exposed to the parent as a property on the
345 child_process object as `ChildProcess.stdio[fd]`. Pipes created for
346 fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
347 and ChildProcess.stderr, respectively.
348 2. `'ipc'` - Create an IPC channel for passing messages/file descriptors
349 between parent and child. A ChildProcess may have at most *one* IPC stdio
350 file descriptor. Setting this option enables the ChildProcess.send() method.
351 If the child writes JSON messages to this file descriptor, then this will
352 trigger ChildProcess.on('message'). If the child is a Node.js program, then
353 the presence of an IPC channel will enable process.send() and
354 process.on('message').
355 3. `'ignore'` - Do not set this file descriptor in the child. Note that Node
356 will always open fd 0 - 2 for the processes it spawns. When any of these is
357 ignored node will open `/dev/null` and attach it to the child's fd.
358 4. `Stream` object - Share a readable or writable stream that refers to a tty,
359 file, socket, or a pipe with the child process. The stream's underlying
360 file descriptor is duplicated in the child process to the fd that
361 corresponds to the index in the `stdio` array.
362 5. Positive integer - The integer value is interpreted as a file descriptor
363 that is is currently open in the parent process. It is shared with the child
364 process, similar to how `Stream` objects can be shared.
365 6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
366 words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
367 default is `'ignore'`.
369 As a shorthand, the `stdio` argument may also be one of the following
370 strings, rather than an array:
372 * `ignore` - `['ignore', 'ignore', 'ignore']`
373 * `pipe` - `['pipe', 'pipe', 'pipe']`
374 * `inherit` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]`
378 var spawn = require('child_process').spawn;
380 // Child will use parent's stdios
381 spawn('prg', [], { stdio: 'inherit' });
383 // Spawn child sharing only stderr
384 spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
386 // Open an extra fd=4, to interact with programs present a
387 // startd-style interface.
388 spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
390 There is a deprecated option called `customFds` which allows one to specify
391 specific file descriptors for the stdio of the child process. This API was
392 not portable to all platforms and therefore removed.
393 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
394 stderr]` to existing streams; `-1` meant that a new stream should be created.
395 Use at your own risk.
397 There are several internal options. In particular `stdinStream`,
398 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
399 undocumented APIs in Node, they should not be used.
401 See also: `child_process.exec()` and `child_process.fork()`
403 ## child_process.exec(command, [options], callback)
405 * `command` {String} The command to run, with space-separated arguments
407 * `cwd` {String} Current working directory of the child process
408 * `stdio` {Array|String} Child's stdio configuration. (See above)
409 * `customFds` {Array} **Deprecated** File descriptors for the child to use
410 for stdio. (See above)
411 * `env` {Object} Environment key-value pairs
413 * `encoding` {String} (Default: 'utf8')
414 * `timeout` {Number} (Default: 0)
415 * `maxBuffer` {Number} (Default: 200*1024)
416 * `killSignal` {String} (Default: 'SIGTERM')
417 * `callback` {Function} called with the output when process terminates
421 * Return: ChildProcess object
423 Runs a command in a shell and buffers the output.
425 var util = require('util'),
426 exec = require('child_process').exec,
429 child = exec('cat *.js bad_file | wc -l',
430 function (error, stdout, stderr) {
431 console.log('stdout: ' + stdout);
432 console.log('stderr: ' + stderr);
433 if (error !== null) {
434 console.log('exec error: ' + error);
438 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
439 will be `null`. On error, `error` will be an instance of `Error` and `err.code`
440 will be the exit code of the child process, and `err.signal` will be set to the
441 signal that terminated the process.
443 There is a second optional argument to specify several options. The
449 killSignal: 'SIGTERM',
453 If `timeout` is greater than 0, then it will kill the child process
454 if it runs longer than `timeout` milliseconds. The child process is killed with
455 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
456 amount of data allowed on stdout or stderr - if this value is exceeded then
457 the child process is killed.
460 ## child_process.execFile(file, args, options, callback)
462 * `file` {String} The filename of the program to run
463 * `args` {Array} List of string arguments
465 * `cwd` {String} Current working directory of the child process
466 * `stdio` {Array|String} Child's stdio configuration. (See above)
467 * `customFds` {Array} **Deprecated** File descriptors for the child to use
468 for stdio. (See above)
469 * `env` {Object} Environment key-value pairs
471 * `encoding` {String} (Default: 'utf8')
472 * `timeout` {Number} (Default: 0)
473 * `maxBuffer` {Number} (Default: 200*1024)
474 * `killSignal` {String} (Default: 'SIGTERM')
475 * `callback` {Function} called with the output when process terminates
479 * Return: ChildProcess object
481 This is similar to `child_process.exec()` except it does not execute a
482 subshell but rather the specified file directly. This makes it slightly
483 leaner than `child_process.exec`. It has the same options.
486 ## child_process.fork(modulePath, [args], [options])
488 * `modulePath` {String} The module to run in the child
489 * `args` {Array} List of string arguments
491 * `cwd` {String} Current working directory of the child process
492 * `env` {Object} Environment key-value pairs
494 * `encoding` {String} (Default: 'utf8')
495 * `timeout` {Number} (Default: 0)
496 * Return: ChildProcess object
498 This is a special case of the `spawn()` functionality for spawning Node
499 processes. In addition to having all the methods in a normal ChildProcess
500 instance, the returned object has a communication channel built-in. See
501 `child.send(message, [sendHandle])` for details.
503 By default the spawned Node process will have the stdout, stderr associated
504 with the parent's. To change this behavior set the `silent` property in the
505 `options` object to `true`.
507 These child Nodes are still whole new instances of V8. Assume at least 30ms
508 startup and 10mb memory for each new Node. That is, you cannot create many