5 The `child_process` module provides the ability to spawn child processes in
6 a manner that is similar, but not identical, to [`popen(3)`][]. This capability
7 is primarily provided by the `child_process.spawn()` function:
9 const spawn = require('child_process').spawn;
10 const ls = spawn('ls', ['-lh', '/usr']);
12 ls.stdout.on('data', (data) => {
13 console.log(`stdout: ${data}`);
16 ls.stderr.on('data', (data) => {
17 console.log(`stderr: ${data}`);
20 ls.on('close', (code) => {
21 console.log(`child process exited with code ${code}`);
24 By default, pipes for `stdin`, `stdout` and `stderr` are established between
25 the parent Node.js process and the spawned child. It is possible to stream data
26 through these pipes in a non-blocking way. *Note, however, that some programs
27 use line-buffered I/O internally. While that does not affect Node.js, it can
28 mean that data sent to the child process may not be immediately consumed.*
30 The `child_process.spawn()` method spawns the child process asynchronously,
31 without blocking the Node.js event loop. The `child_process.spawnSync()`
32 function provides equivalent functionality in a synchronous manner that blocks
33 the event loop until the spawned process either exits of is terminated.
35 For convenience, the `child_process` module provides a handful of synchronous
36 and asynchronous alternatives to `child_process.spawn()` and
37 `child_process.spawnSync()`, each of which are documented fully [below][].
38 *Note that each of these alternatives are implemented on top of
39 `child_process.spawn()` or `child_process.spawnSync()`.*
41 * `child_process.exec()`: spawns a shell and runs a command within that shell,
42 passing the `stdout` and `stderr` to a callback function when complete.
43 * `child_process.execFile()`: similar to `child_process.exec()` except that
44 it spawns the command directly without first spawning a shell.
45 * `child_process.fork()`: spawns a new Node.js process and invokes a
46 specified module with an IPC communication channel established that allows
47 sending messages between parent and child.
48 * `child_process.execSync()`: a synchronous version of
49 `child_process.exec()` that *will* block the Node.js event loop.
50 * `child_process.execFileSync()`: a synchronous version of
51 `child_process.execFile()` that *will* block the Node.js event loop.
53 For certain use cases, such as automating shell scripts, the
54 [synchronous counterparts][] may be more convenient. In many cases, however,
55 the synchronous methods can have significant impact on performance due to
56 stalling the event loop while spawned processes complete.
58 ## Asynchronous Process Creation
60 The `child_process.spawn()`, `child_process.fork()`, `child_process.exec()`,
61 and `child_process.execFile()` methods all follow the idiomatic asynchronous
62 programming pattern typical of other Node.js APIs.
64 Each of the methods returns a [ChildProcess][] instance. These objects
65 implement the Node.js [EventEmitter][] API, allowing the parent process to
66 register listener functions that are called when certain events occur during
67 the life cycle of the child process.
69 The `child_process.exec()` and `child_process.execFile()` methods additionally
70 allow for an optional `callback` function to be specified that is invoked
71 when the child process terminates.
73 ### Spawning `.bat` and `.cmd` files on Windows
75 The importance of the distinction between `child_process.exec()` and
76 `child_process.execFile()` can vary based on platform. On Unix-type operating
77 systems (Unix, Linux, OSX) `child_process.execFile()` can be more efficient
78 because it does not spawn a shell. On Windows, however, `.bat` and `.cmd`
79 files are not executable on their own without a terminal and therefore cannot
80 be launched using `child_process.execFile()` (or even `child_process.spawn()`).
81 When running on Windows, `.bat` and `.cmd` files can only be invoked using
82 either `child_process.exec()` or by spawning `cmd.exe` and passing the `.bat`
83 or `.cmd` file as an argument (which is what `child_process.exec()` does).
85 // On Windows Only ...
86 const spawn = require('child_process').spawn;
87 const bat = spawn('cmd.exe', ['/c', 'my.bat']);
89 bat.stdout.on('data', (data) => {
93 bat.stderr.on('data', (data) => {
97 bat.on('exit', (code) => {
98 console.log(`Child exited with code ${code}`);
102 const exec = require('child_process').exec;
103 exec('my.bat', (err, stdout, stderr) => {
111 ### child_process.exec(command[, options][, callback])
113 * `command` {String} The command to run, with space-separated arguments
115 * `cwd` {String} Current working directory of the child process
116 * `env` {Object} Environment key-value pairs
117 * `encoding` {String} (Default: 'utf8')
118 * `shell` {String} Shell to execute the command with
119 (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should
120 understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows,
121 command line parsing should be compatible with `cmd.exe`.)
122 * `timeout` {Number} (Default: 0)
123 * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
124 stderr - if exceeded child process is killed (Default: `200*1024`)
125 * `killSignal` {String} (Default: 'SIGTERM')
126 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
127 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
128 * `callback` {Function} called with the output when process terminates
132 * Return: ChildProcess object
134 Spawns a shell then executes the `command` within that shell, buffering any
137 const exec = require('child_process').exec;
138 const child = exec('cat *.js bad_file | wc -l',
139 (error, stdout, stderr) => {
140 console.log(`stdout: ${stdout}`);
141 console.log(`stderr: ${stderr}`);
142 if (error !== null) {
143 console.log(`exec error: ${error}`);
147 If a `callback` function is provided, it is called with the arguments
148 `(error, stdout, stderr)`. On success, `error` will be `null`. On error,
149 `error` will be an instance of [`Error`][]. The `error.code` property will be
150 the exit code of the child process while `error.signal` will be set to the
151 signal that terminated the process. Any exit code other than `0` is considered
154 The `options` argument may be passed as the second argument to customize how
155 the process is spawned. The default options are:
161 killSignal: 'SIGTERM',
166 If `timeout` is greater than `0`, the parent will send the the signal
167 identified by the `killSignal` property (the default is `'SIGTERM'`) if the
168 child runs longer than `timeout` milliseconds.
170 The `maxBuffer` option specifies the largest amount of data (in bytes) allowed
171 on stdout or stderr - if this value is exceeded then the child process is
174 *Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not
175 replace the existing process and uses a shell to execute the command.*
177 ### child_process.execFile(file[, args][, options][, callback])
179 * `file` {String} The filename of the program to run
180 * `args` {Array} List of string arguments
182 * `cwd` {String} Current working directory of the child process
183 * `env` {Object} Environment key-value pairs
184 * `encoding` {String} (Default: 'utf8')
185 * `timeout` {Number} (Default: 0)
186 * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
187 stderr - if exceeded child process is killed (Default: 200\*1024)
188 * `killSignal` {String} (Default: 'SIGTERM')
189 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
190 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
191 * `callback` {Function} called with the output when process terminates
195 * Return: ChildProcess object
197 The `child_process.execFile()` method is similar to [`child_process.exec()`][]
198 except that it does not first spawn a shell. Rather, the specified `command` is
199 spawned directly as a new process making it slightly more efficient than
200 [`child_process.exec()`][]. The same options are support by both
201 `child_process.exec()` and `child_process.execFile()`.
203 const exec = require('child_process').execFile;
204 const child = execFile('cat *.js bad_file | wc -l',
205 (error, stdout, stderr) => {
206 console.log(`stdout: ${stdout}`);
207 console.log(`stderr: ${stderr}`);
208 if (error !== null) {
209 console.log(`exec error: ${error}`);
213 ### child_process.fork(modulePath[, args][, options])
215 * `modulePath` {String} The module to run in the child
216 * `args` {Array} List of string arguments
218 * `cwd` {String} Current working directory of the child process
219 * `env` {Object} Environment key-value pairs
220 * `execPath` {String} Executable used to create the child process
221 * `execArgv` {Array} List of string arguments passed to the executable
222 (Default: `process.execArgv`)
223 * `silent` {Boolean} If true, stdin, stdout, and stderr of the child will be
224 piped to the parent, otherwise they will be inherited from the parent, see
225 the `'pipe'` and `'inherit'` options for [`spawn()`][]'s [`stdio`][] for more details
227 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
228 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
229 * Return: ChildProcess object
231 The `child_process.fork()` method is a special case of
232 [`child_process.spawn()`][] used specifically to spawn new Node.js processes.
233 Like `child_process.spawn()`, a `ChildProcess` object is returned. The returned
234 `ChildProcess` will have an additional communication channel built-in that
235 allows messages to be passed back and forth between the parent and child. See
236 [`ChildProcess#send()`][] for details.
238 It is important to keep in mind that spawned Node.js child processes are
239 independent of the parent with exception of the IPC communication channel
240 that is established between the two. Each process has it's own memory, with
241 their own V8 instances. Because of the additional resource allocations
242 required, spawning a large number of child Node.js processes is not
245 By default, `child_process.fork()` will spawn new Node.js instances using the
246 `process.execPath` of the parent process. The `execPath` property in the
247 `options` object allows for an alternative execution path to be used.
249 Node.js processes launched with a custom `execPath` will communicate with the
250 parent process using the file descriptor (fd) identified using the
251 environment variable `NODE_CHANNEL_FD` on the child process. The input and
252 output on this fd is expected to be line delimited JSON objects.
254 *Note: Unlike the `fork()` POSIX system call, [`child_process.fork()`][] does
255 not clone the current process.*
257 ### child_process.spawn(command[, args][, options])
259 * `command` {String} The command to run
260 * `args` {Array} List of string arguments
262 * `cwd` {String} Current working directory of the child process
263 * `env` {Object} Environment key-value pairs
264 * `stdio` {Array|String} Child's stdio configuration. (See
265 [below](#child_process_options_stdio))
266 * `detached` {Boolean} Prepare child to run independently of its parent
267 process. Specific behavior depends on the platform, see
268 [below](#child_process_options_detached))
269 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
270 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
271 * return: {ChildProcess object}
273 The `child_process.spawn()` method spawns a new process using the given
274 `command`, with command line arguments in `args`. If omitted, `args` defaults
277 A third argument may be used to specify additional options, with these defaults:
284 Use `cwd` to specify the working directory from which the process is spawned.
285 If not given, the default is to inherit the current working directory.
287 Use `env` to specify environment variables that will be visible to the new
288 process, the default is `process.env`.
290 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
293 const spawn = require('child_process').spawn;
294 const ls = spawn('ls', ['-lh', '/usr']);
296 ls.stdout.on('data', (data) => {
297 console.log(`stdout: ${data}`);
300 ls.stderr.on('data', (data) => {
301 console.log(`stderr: ${data}`);
304 ls.on('close', (code) => {
305 console.log(`child process exited with code ${code}`);
309 Example: A very elaborate way to run 'ps ax | grep ssh'
311 const spawn = require('child_process').spawn;
312 const ps = spawn('ps', ['ax']);
313 const grep = spawn('grep', ['ssh']);
315 ps.stdout.on('data', (data) => {
316 grep.stdin.write(data);
319 ps.stderr.on('data', (data) => {
320 console.log(`ps stderr: ${data}`);
323 ps.on('close', (code) => {
325 console.log(`ps process exited with code ${code}`);
330 grep.stdout.on('data', (data) => {
331 console.log(`${data}`);
334 grep.stderr.on('data', (data) => {
335 console.log(`grep stderr: ${data}`);
338 grep.on('close', (code) => {
340 console.log(`grep process exited with code ${code}`);
345 Example of checking for failed exec:
347 const spawn = require('child_process').spawn;
348 const child = spawn('bad_command');
350 child.on('error', (err) => {
351 console.log('Failed to start child process.');
354 #### options.detached
356 On Windows, setting `options.detached` to `true` makes it possible for the
357 child process to continue running after the parent exits. The child will have
358 its own console window. *Once enabled for a child process, it cannot be
361 On non-Windows platforms, if `options.detached` is set to `true`, the child
362 process will be made the leader of a new process group and session. Note that
363 child processes may continue running after the parent exits regardless of
364 whether they are detached or not. See `setsid(2)` for more information.
366 By default, the parent will wait for the detached child to exit. To prevent
367 the parent from waiting for a given `child`, use the `child.unref()` method.
368 Doing so will cause the parent's event loop to not include the child in its
369 reference count, allowing the parent to exit independently of the child, unless
370 there is an established IPC channel between the child and parent.
372 Example of detaching a long-running process and redirecting its output to a
375 const fs = require('fs');
376 const spawn = require('child_process').spawn;
377 const out = fs.openSync('./out.log', 'a');
378 const err = fs.openSync('./out.log', 'a');
380 const child = spawn('prg', [], {
382 stdio: [ 'ignore', out, err ]
387 When using the `detached` option to start a long-running process, the process
388 will not stay running in the background after the parent exits unless it is
389 provided with a `stdio` configuration that is not connected to the parent.
390 If the parent's `stdio` is inherited, the child will remain attached to the
391 controlling terminal.
395 The `options.stdio` option is used to configure the pipes that are established
396 between the parent and child process. By default, the child's stdin, stdout,
397 and stderr are redirected to corresponding `child.stdin`, `child.stdout`, and
398 `child.stderr` streams on the `ChildProcess` object. This is equivalent to
399 setting the `options.stdio` equal to `['pipe', 'pipe', 'pipe']`.
401 For convenience, `options.stdio` may be one of the following strings:
403 * `'pipe'` - equivalent to `['pipe', 'pipe', 'pipe']` (the default)
404 * `'ignore'` - equivalent to `['ignore', 'ignore', 'ignore']`
405 * `'inherit'` - equivalent to `[process.stdin, process.stdout, process.stderr]`
408 Otherwise, the value of `option.stdio` is an array where each index corresponds
409 to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
410 and stderr, respectively. Additional fds can be specified to create additional
411 pipes between the parent and child. The value is one of the following:
413 1. `'pipe'` - Create a pipe between the child process and the parent process.
414 The parent end of the pipe is exposed to the parent as a property on the
415 `child_process` object as `ChildProcess.stdio[fd]`. Pipes created for
416 fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
417 and ChildProcess.stderr, respectively.
418 2. `'ipc'` - Create an IPC channel for passing messages/file descriptors
419 between parent and child. A ChildProcess may have at most *one* IPC stdio
420 file descriptor. Setting this option enables the ChildProcess.send() method.
421 If the child writes JSON messages to this file descriptor, the
422 `ChildProcess.on('message')` event handler will be triggered in the parent.
423 If the child is a Node.js process, the presence of an IPC channel will enable
424 `process.send()`, `process.disconnect()`, `process.on('disconnect')`, and
425 `process.on('message')` within the child.
426 3. `'ignore'` - Instructs Node.js to ignore the fd in the child. While Node.js
427 will always open fds 0 - 2 for the processes it spawns, setting the fd to
428 `'ignore'` will cause Node.js to open `/dev/null` and attach it to the
430 4. `Stream` object - Share a readable or writable stream that refers to a tty,
431 file, socket, or a pipe with the child process. The stream's underlying
432 file descriptor is duplicated in the child process to the fd that
433 corresponds to the index in the `stdio` array. Note that the stream must
434 have an underlying descriptor (file streams do not until the `'open'`
436 5. Positive integer - The integer value is interpreted as a file descriptor
437 that is is currently open in the parent process. It is shared with the child
438 process, similar to how `Stream` objects can be shared.
439 6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
440 words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
441 default is `'ignore'`.
445 const spawn = require('child_process').spawn;
447 // Child will use parent's stdios
448 spawn('prg', [], { stdio: 'inherit' });
450 // Spawn child sharing only stderr
451 spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
453 // Open an extra fd=4, to interact with programs presenting a
454 // startd-style interface.
455 spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
457 *It is worth noting that when an IPC channel is established between the
458 parent and child processes, and the child is a Node.js process, the child
459 is launched with the IPC channel unreferenced (using `unref()`) until the
460 child registers an event handler for the `process.on('disconnected')` event.
461 This allows the child to exit normally without the process being held open
462 by the open IPC channel.*
464 See also: [`child_process.exec()`][] and [`child_process.fork()`][]
466 ## Synchronous Process Creation
468 The `child_process.spawnSync()`, `child_process.execSync()`, and
469 `child_process.execFileSync()` methods are **synchronous** and **WILL** block
470 the Node.js event loop, pausing execution of any additional code until the
471 spawned process exits.
473 Blocking calls like these are mostly useful for simplifying general purpose
474 scripting tasks and for simplifying the loading/processing of application
475 configuration at startup.
477 ### child_process.execFileSync(file[, args][, options])
479 * `file` {String} The filename of the program to run
480 * `args` {Array} List of string arguments
482 * `cwd` {String} Current working directory of the child process
483 * `input` {String|Buffer} The value which will be passed as stdin to the spawned process
484 - supplying this value will override `stdio[0]`
485 * `stdio` {Array} Child's stdio configuration. (Default: 'pipe')
486 - `stderr` by default will be output to the parent process' stderr unless
488 * `env` {Object} Environment key-value pairs
489 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
490 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
491 * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)
492 * `killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')
493 * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
494 stderr - if exceeded child process is killed
495 * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
496 * return: {Buffer|String} The stdout from the command
498 The `child_process.execFileSync()` method is generally identical to
499 `child_process.execFile()` with the exception that the method will not return
500 until the child process has fully closed. When a timeout has been encountered
501 and `killSignal` is sent, the method won't return until the process has
502 completely exited. *Note that if the child process intercepts and handles
503 the `SIGTERM` signal and does not exit, the parent process will still wait
504 until the child process has exited.*
506 If the process times out, or has a non-zero exit code, this method ***will***
507 throw. The [`Error`][] object will contain the entire result from
508 [`child_process.spawnSync()`][]
510 ### child_process.execSync(command[, options])
512 * `command` {String} The command to run
514 * `cwd` {String} Current working directory of the child process
515 * `input` {String|Buffer} The value which will be passed as stdin to the spawned process
516 - supplying this value will override `stdio[0]`
517 * `stdio` {Array} Child's stdio configuration. (Default: 'pipe')
518 - `stderr` by default will be output to the parent process' stderr unless
520 * `env` {Object} Environment key-value pairs
521 * `shell` {String} Shell to execute the command with
522 (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should
523 understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows,
524 command line parsing should be compatible with `cmd.exe`.)
525 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
526 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
527 * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)
528 * `killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')
529 * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
530 stderr - if exceeded child process is killed
531 * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
532 * return: {Buffer|String} The stdout from the command
534 The `child_process.execSync()` method is generally identical to
535 `child_process.exec()` with the exception that the method will not return until
536 the child process has fully closed. When a timeout has been encountered and
537 `killSignal` is sent, the method won't return until the process has completely
538 exited. *Note that if the child process intercepts and handles the `SIGTERM`
539 signal and doesn't exit, the parent process will wait until the child
542 If the process times out, or has a non-zero exit code, this method ***will***
543 throw. The [`Error`][] object will contain the entire result from
544 [`child_process.spawnSync()`][]
546 ### child_process.spawnSync(command[, args][, options])
548 * `command` {String} The command to run
549 * `args` {Array} List of string arguments
551 * `cwd` {String} Current working directory of the child process
552 * `input` {String|Buffer} The value which will be passed as stdin to the spawned process
553 - supplying this value will override `stdio[0]`
554 * `stdio` {Array} Child's stdio configuration.
555 * `env` {Object} Environment key-value pairs
556 * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
557 * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
558 * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)
559 * `killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')
560 * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
561 stderr - if exceeded child process is killed
562 * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
564 * `pid` {Number} Pid of the child process
565 * `output` {Array} Array of results from stdio output
566 * `stdout` {Buffer|String} The contents of `output[1]`
567 * `stderr` {Buffer|String} The contents of `output[2]`
568 * `status` {Number} The exit code of the child process
569 * `signal` {String} The signal used to kill the child process
570 * `error` {Error} The error object if the child process failed or timed out
572 The `child_process.spawnSync()` method is generally identical to
573 `child_process.spawn()` with the exception that the function will not return
574 until the child process has fully closed. When a timeout has been encountered
575 and `killSignal` is sent, the method won't return until the process has
576 completely exited. Note that if the process intercepts and handles the
577 `SIGTERM` signal and doesn't exit, the parent process will wait until the child
580 ## Class: ChildProcess
582 Instances of the `ChildProcess` class are [`EventEmitters`][] that represent
583 spawned child processes.
585 Instances of `ChildProcess` are not intended to be created directly. Rather,
586 use the [`child_process.spawn()`][], [`child_process.exec()`][],
587 [`child_process.execFile()`][], or [`child_process.fork()`][] methods to create
588 instances of `ChildProcess`.
592 * `code` {Number} the exit code if the child exited on its own.
593 * `signal` {String} the signal by which the child process was terminated.
595 The `'close'` event is emitted when the stdio streams of a child process have
596 been closed. This is distinct from the `'exit'` event, since multiple
597 processes might share the same stdio streams.
599 ### Event: 'disconnect'
601 The `'disconnect'` event is emitted after calling the
602 `ChildProcess.disconnect()` method in the parent or child process. After
603 disconnecting it is no longer possible to send or receive messages, and the
604 `ChildProcess.connected` property is false.
608 * `err` {Error Object} the error.
610 The `'error'` event is emitted whenever:
612 1. The process could not be spawned, or
613 2. The process could not be killed, or
614 3. Sending a message to the child process failed.
616 Note that the `'exit'` event may or may not fire after an error has occurred.
617 If you are listening to both the `'exit'` and `'error'` events, it is important
618 to guard against accidentally invoking handler functions multiple times.
620 See also [`ChildProcess#kill()`][] and [`ChildProcess#send()`][].
624 * `code` {Number} the exit code if the child exited on its own.
625 * `signal` {String} the signal by which the child process was terminated.
627 The `'exit'` event is emitted after the child process ends. If the process
628 exited, `code` is the final exit code of the process, otherwise `null`. If the
629 process terminated due to receipt of a signal, `signal` is the string name of
630 the signal, otherwise `null`. One of the two will always be non-null.
632 Note that when the `'exit'` event is triggered, child process stdio streams
635 Also, note that Node.js establishes signal handlers for `SIGINT` and
636 `SIGTERM` and Node.js processes will not terminate immediately due to receipt
637 of those signals. Rather, Node.js will perform a sequence of cleanup actions
638 and then will re-raise the handled signal.
644 * `message` {Object} a parsed JSON object or primitive value.
645 * `sendHandle` {Handle object} a [`net.Socket`][] or [`net.Server`][] object, or
648 The `'message'` event is triggered when a child process uses `process.send()`
653 * {Boolean} Set to false after `.disconnect` is called
655 The `child.connected` property indicates whether it is still possible to send
656 and receive messages from a child process. When `child.connected` is false, it
657 is no longer possible to send or receive messages.
659 ### child.disconnect()
661 Closes the IPC channel between parent and child, allowing the child to exit
662 gracefully once there are no other connections keeping it alive. After calling
663 this method the `child.connected` and `process.connected` properties in both
664 the parent and child (respectively) will be set to `false`, and it will be no
665 longer possible to pass messages between the processes.
667 The `'disconnect'` event will be emitted when there are no messages in the
668 process of being received. This will most often be triggered immediately after
669 calling `child.disconnect()`.
671 Note that when the child process is a Node.js instance (e.g. spawned using
672 [`child_process.fork()`]), the `process.disconnect()` method can be invoked
673 within the child process to close the IPC channel as well.
675 ### child.kill([signal])
679 The `child.kill()` methods sends a signal to the child process. If no argument
680 is given, the process will be sent the `'SIGTERM'` signal. See `signal(7)` for
681 a list of available signals.
683 const spawn = require('child_process').spawn;
684 const grep = spawn('grep', ['ssh']);
686 grep.on('close', (code, signal) => {
688 `child process terminated due to receipt of signal ${signal}`);
691 // Send SIGHUP to process
694 The `ChildProcess` object may emit an `'error'` event if the signal cannot be
695 delivered. Sending a signal to a child process that has already exited is not
696 an error but may have unforeseen consequences. Specifically, if the process
697 identifier (PID) has been reassigned to another process, the signal will be
698 delivered to that process instead which can have unexpected results.
700 Note that while the function is called `kill`, the signal delivered to the
701 child process may not actually terminate the process.
709 Returns the process identifier (PID) of the child process.
713 const spawn = require('child_process').spawn;
714 const grep = spawn('grep', ['ssh']);
716 console.log(`Spawned child pid: ${grep.pid}`);
719 ### child.send(message[, sendHandle][, callback])
722 * `sendHandle` {Handle object}
723 * `callback` {Function}
726 When an IPC channel has been established between the parent and child (
727 i.e. when using [`child_process.fork()`][]), the `child.send()` method can be
728 used to send messages to the child process. When the child process is a Node.js
729 instance, these messages can be received via the `process.on('message')` event.
731 For example, in the parent script:
733 const cp = require('child_process');
734 const n = cp.fork(`${__dirname}/sub.js`);
736 n.on('message', (m) => {
737 console.log('PARENT got message:', m);
740 n.send({ hello: 'world' });
742 And then the child script, `'sub.js'` might look like this:
744 process.on('message', (m) => {
745 console.log('CHILD got message:', m);
748 process.send({ foo: 'bar' });
750 Child Node.js processes will have a `process.send()` method of their own that
751 allows the child to send messages back to the parent.
753 There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
754 containing a `NODE_` prefix in its `cmd` property are considered to be reserved
755 for use within Node.js core and will not be emitted in the child's
756 `process.on('message')` event. Rather, such messages are emitted using the
757 `process.on('internalMessage')` event and are consumed internally by Node.js.
758 Applications should avoid using such messages or listening for
759 `'internalMessage'` events as it is subject to change without notice.
761 The optional `sendHandle` argument that may be passed to `child.send()` is for
762 passing a TCP server or socket object to the child process. The child will
763 receive the object as the second argument passed to the callback function
764 registered on the `process.on('message')` event.
766 The optional `callback` is a function that is invoked after the message is
767 sent but before the child may have received it. The function is called with a
768 single argument: `null` on success, or an [`Error`][] object on failure.
770 If no `callback` function is provided and the message cannot be sent, an
771 `'error'` event will be emitted by the `ChildProcess` object. This can happen,
772 for instance, when the child process has already exited.
774 `child.send()` will return `false` if the channel has closed or when the
775 backlog of unsent messages exceeds a threshold that makes it unwise to send
776 more. Otherwise, the method returns `true`. The `callback` function can be
777 used to implement flow control.
779 #### Example: sending a server object
781 The `sendHandle` argument can be used, for instance, to pass the handle of
782 a TSCP server object to the child process as illustrated in the example below:
784 const child = require('child_process').fork('child.js');
786 // Open up the server object and send the handle.
787 const server = require('net').createServer();
788 server.on('connection', (socket) => {
789 socket.end('handled by parent');
791 server.listen(1337, () => {
792 child.send('server', server);
795 The child would then receive the server object as:
797 process.on('message', (m, server) => {
798 if (m === 'server') {
799 server.on('connection', (socket) => {
800 socket.end('handled by child');
805 Once the server is now shared between the parent and child, some connections
806 can be handled by the parent and some by the child.
808 While the example above uses a server created using the `net` module, `dgram`
809 module servers use exactly the same workflow with the exceptions of listening on
810 a `'message'` event instead of `'connection'` and using `server.bind` instead of
811 `server.listen`. This is, however, currently only supported on UNIX platforms.
813 #### Example: sending a socket object
815 Similarly, the `sendHandler` argument can be used to pass the handle of a
816 socket to the child process. The example below spawns two children that each
817 handle connections with "normal" or "special" priority:
819 const normal = require('child_process').fork('child.js', ['normal']);
820 const special = require('child_process').fork('child.js', ['special']);
822 // Open up the server and send sockets to child
823 const server = require('net').createServer();
824 server.on('connection', (socket) => {
826 // If this is special priority
827 if (socket.remoteAddress === '74.125.127.100') {
828 special.send('socket', socket);
831 // This is normal priority
832 normal.send('socket', socket);
836 The `child.js` would receive the socket handle as the second argument passed
837 to the event callback function:
839 process.on('message', (m, socket) => {
840 if (m === 'socket') {
841 socket.end(`Request handled with ${process.argv[2]} priority`);
845 Once a socket has been passed to a child, the parent is no longer capable of
846 tracking when the socket is destroyed. To indicate this, the `.connections`
847 property becomes `null`. It is recommended not to use `.maxConnections` when
854 A `Readable Stream` that represents the child process's `stderr`.
856 If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
857 then this will be `undefined`.
859 `child.stderr` is an alias for `child.stdio[2]`. Both properties will refer to
866 A `Writable Stream` that represents the child process's `stdin`.
868 *Note that if a child process waits to read all of its input, the child will not
869 continue until this stream has been closed via `end()`.*
871 If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
872 then this will be `undefined`.
874 `child.stdin` is an alias for `child.stdio[0]`. Both properties will refer to
881 A sparse array of pipes to the child process, corresponding with positions in
882 the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
883 to the value `'pipe'`. Note that `child.stdio[0]`, `child.stdio[1]`, and
884 `child.stdio[2]` are also available as `child.stdin`, `child.stdout`, and
885 `child.stderr`, respectively.
887 In the following example, only the child's fd `1` (stdout) is configured as a
888 pipe, so only the parent's `child.stdio[1]` is a stream, all other values in
889 the array are `null`.
891 const assert = require('assert');
892 const fs = require('fs');
893 const child_process = require('child_process');
895 const child = child_process.spawn('ls', {
897 0, // Use parents stdin for child
898 'pipe', // Pipe child's stdout to parent
899 fs.openSync('err.out', 'w') // Direct child's stderr to a file
903 assert.equal(child.stdio[0], null);
904 assert.equal(child.stdio[0], child.stdin);
906 assert(child.stdout);
907 assert.equal(child.stdio[1], child.stdout);
909 assert.equal(child.stdio[2], null);
910 assert.equal(child.stdio[2], child.stderr);
916 A `Readable Stream` that represents the child process's `stdout`.
918 If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
919 then this will be `undefined`.
921 `child.stdout` is an alias for `child.stdio[1]`. Both properties will refer
924 [`popen(3)`]: http://linux.die.net/man/3/popen
925 [`child_process.exec()`]: #child_process_child_process_exec_command_options_callback
926 [`child_process.execFile()`]: #child_process_child_process_execfile_file_args_options_callback
927 [`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
928 [`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options
929 [`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options
930 [`ChildProcess#kill()`]: #child_process_child_kill_signal
931 [`ChildProcess#send()`]: #child_process_child_send_message_sendhandle_callback
932 [`Error`]: errors.html#errors_class_error
933 [`EventEmitters`]: events.html#events_class_events_eventemitter
934 [`net.Server`]: net.html#net_class_net_server
935 [`net.Socket`]: net.html#net_class_net_socket
936 [`stdio`]: #child_process_options_stdio
937 [below]: #child_process_asynchronous_process_creation
938 [synchronous counterparts]: #child_process_synchronous_process_creation