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 handle 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 useing `child_process.fork()` an 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 handle object to
166 another process. The child will receive the object as its second argument to
169 ### child.disconnect()
171 To close the IPC connection between parent and child use the
172 `child.disconnect()` method. This allows the child to exit gracefully since
173 there is no IPC channel keeping it alive. When calling this method the
174 `disconnect` event will be emitted in both parent and child, and the
175 `connected` flag will be set to `false`. Please note that you can also call
176 `process.disconnect()` in the child process.
178 ## child_process.spawn(command, [args], [options])
180 * `command` {String} The command to run
181 * `args` {Array} List of string arguments
183 * `cwd` {String} Current working directory of the child process
184 * `customFds` {Array} **Deprecated** File descriptors for the child to use
185 for stdio. (See below)
186 * `env` {Object} Environment key-value pairs
188 * return: {ChildProcess object}
190 Launches a new process with the given `command`, with command line arguments in `args`.
191 If omitted, `args` defaults to an empty Array.
193 The third argument is used to specify additional options, which defaults to:
199 `cwd` allows you to specify the working directory from which the process is spawned.
200 Use `env` to specify environment variables that will be visible to the new process.
202 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
204 var util = require('util'),
205 spawn = require('child_process').spawn,
206 ls = spawn('ls', ['-lh', '/usr']);
208 ls.stdout.on('data', function (data) {
209 console.log('stdout: ' + data);
212 ls.stderr.on('data', function (data) {
213 console.log('stderr: ' + data);
216 ls.on('exit', function (code) {
217 console.log('child process exited with code ' + code);
221 Example: A very elaborate way to run 'ps ax | grep ssh'
223 var util = require('util'),
224 spawn = require('child_process').spawn,
225 ps = spawn('ps', ['ax']),
226 grep = spawn('grep', ['ssh']);
228 ps.stdout.on('data', function (data) {
229 grep.stdin.write(data);
232 ps.stderr.on('data', function (data) {
233 console.log('ps stderr: ' + data);
236 ps.on('exit', function (code) {
238 console.log('ps process exited with code ' + code);
243 grep.stdout.on('data', function (data) {
247 grep.stderr.on('data', function (data) {
248 console.log('grep stderr: ' + data);
251 grep.on('exit', function (code) {
253 console.log('grep process exited with code ' + code);
258 Example of checking for failed exec:
260 var spawn = require('child_process').spawn,
261 child = spawn('bad_command');
263 child.stderr.setEncoding('utf8');
264 child.stderr.on('data', function (data) {
265 if (/^execvp\(\)/.test(data)) {
266 console.log('Failed to start child process.');
270 Note that if spawn receives an empty options object, it will result in
271 spawning the process with an empty environment rather than using
272 `process.env`. This due to backwards compatibility issues with a deprecated
275 There is a deprecated option called `customFds` which allows one to specify
276 specific file descriptors for the stdio of the child process. This API was
277 not portable to all platforms and therefore removed.
278 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
279 stderr]` to existing streams; `-1` meant that a new stream should be created.
280 Use at your own risk.
282 There are several internal options. In particular `stdinStream`,
283 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
284 undocumented APIs in Node, they should not be used.
286 See also: `child_process.exec()` and `child_process.fork()`
288 ## child_process.exec(command, [options], callback)
290 * `command` {String} The command to run, with space-separated arguments
292 * `cwd` {String} Current working directory of the child process
293 * `customFds` {Array} **Deprecated** File descriptors for the child to use
294 for stdio. (See below)
295 * `env` {Object} Environment key-value pairs
297 * `encoding` {String} (Default: 'utf8')
298 * `timeout` {Number} (Default: 0)
299 * `maxBuffer` {Number} (Default: 200*1024)
300 * `killSignal` {String} (Default: 'SIGTERM')
301 * `callback` {Function} called with the output when process terminates
305 * Return: ChildProcess object
307 Runs a command in a shell and buffers the output.
309 var util = require('util'),
310 exec = require('child_process').exec,
313 child = exec('cat *.js bad_file | wc -l',
314 function (error, stdout, stderr) {
315 console.log('stdout: ' + stdout);
316 console.log('stderr: ' + stderr);
317 if (error !== null) {
318 console.log('exec error: ' + error);
322 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
323 will be `null`. On error, `error` will be an instance of `Error` and `err.code`
324 will be the exit code of the child process, and `err.signal` will be set to the
325 signal that terminated the process.
327 There is a second optional argument to specify several options. The
333 killSignal: 'SIGTERM',
337 If `timeout` is greater than 0, then it will kill the child process
338 if it runs longer than `timeout` milliseconds. The child process is killed with
339 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
340 amount of data allowed on stdout or stderr - if this value is exceeded then
341 the child process is killed.
344 ## child_process.execFile(file, args, options, callback)
346 * `file` {String} The filename of the program to run
347 * `args` {Array} List of string arguments
349 * `cwd` {String} Current working directory of the child process
350 * `customFds` {Array} **Deprecated** File descriptors for the child to use
351 for stdio. (See below)
352 * `env` {Object} Environment key-value pairs
354 * `encoding` {String} (Default: 'utf8')
355 * `timeout` {Number} (Default: 0)
356 * `maxBuffer` {Number} (Default: 200*1024)
357 * `killSignal` {String} (Default: 'SIGTERM')
358 * `callback` {Function} called with the output when process terminates
362 * Return: ChildProcess object
364 This is similar to `child_process.exec()` except it does not execute a
365 subshell but rather the specified file directly. This makes it slightly
366 leaner than `child_process.exec`. It has the same options.
369 ## child_process.fork(modulePath, [args], [options])
371 * `modulePath` {String} The module to run in the child
372 * `args` {Array} List of string arguments
374 * `cwd` {String} Current working directory of the child process
375 * `customFds` {Array} **Deprecated** File descriptors for the child to use
376 for stdio. (See below)
377 * `env` {Object} Environment key-value pairs
379 * `encoding` {String} (Default: 'utf8')
380 * `timeout` {Number} (Default: 0)
381 * Return: ChildProcess object
383 This is a special case of the `spawn()` functionality for spawning Node
384 processes. In addition to having all the methods in a normal ChildProcess
385 instance, the returned object has a communication channel built-in. Se
386 `child.send(message, [sendHandle])` for details.
388 By default the spawned Node process will have the stdout, stderr associated
389 with the parent's. To change this behavior set the `silent` property in the
390 `options` object to `true`.
392 These child Nodes are still whole new instances of V8. Assume at least 30ms
393 startup and 10mb memory for each new Node. That is, you cannot create many