revise installing a license file
[platform/upstream/nodejs.git] / doc / api / child_process.markdown
1 # Child Process
2
3     Stability: 2 - Stable
4
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:
8
9 ```js
10 const spawn = require('child_process').spawn;
11 const ls = spawn('ls', ['-lh', '/usr']);
12
13 ls.stdout.on('data', (data) => {
14   console.log(`stdout: ${data}`);
15 });
16
17 ls.stderr.on('data', (data) => {
18   console.log(`stderr: ${data}`);
19 });
20
21 ls.on('close', (code) => {
22   console.log(`child process exited with code ${code}`);
23 });
24 ```
25
26 By default, pipes for `stdin`, `stdout` and `stderr` are established between
27 the parent Node.js process and the spawned child. It is possible to stream data
28 through these pipes in a non-blocking way. *Note, however, that some programs
29 use line-buffered I/O internally. While that does not affect Node.js, it can
30 mean that data sent to the child process may not be immediately consumed.*
31
32 The `child_process.spawn()` method spawns the child process asynchronously,
33 without blocking the Node.js event loop. The `child_process.spawnSync()`
34 function provides equivalent functionality in a synchronous manner that blocks
35 the event loop until the spawned process either exits or is terminated.
36
37 For convenience, the `child_process` module provides a handful of synchronous
38 and asynchronous alternatives to [`child_process.spawn()`][] and
39 [`child_process.spawnSync()`][].  *Note that each of these alternatives are
40 implemented on top of `child_process.spawn()` or `child_process.spawnSync()`.*
41
42   * `child_process.exec()`: spawns a shell and runs a command within that shell,
43     passing the `stdout` and `stderr` to a callback function when complete.
44   * `child_process.execFile()`: similar to `child_process.exec()` except that
45     it spawns the command directly without first spawning a shell.
46   * `child_process.fork()`: spawns a new Node.js process and invokes a
47     specified module with an IPC communication channel established that allows
48     sending messages between parent and child.
49   * `child_process.execSync()`: a synchronous version of
50     `child_process.exec()` that *will* block the Node.js event loop.
51   * `child_process.execFileSync()`: a synchronous version of
52     `child_process.execFile()` that *will* block the Node.js event loop.
53
54 For certain use cases, such as automating shell scripts, the
55 [synchronous counterparts][] may be more convenient. In many cases, however,
56 the synchronous methods can have significant impact on performance due to
57 stalling the event loop while spawned processes complete.
58
59 ## Asynchronous Process Creation
60
61 The `child_process.spawn()`, `child_process.fork()`, `child_process.exec()`,
62 and `child_process.execFile()` methods all follow the idiomatic asynchronous
63 programming pattern typical of other Node.js APIs.
64
65 Each of the methods returns a [`ChildProcess`][] instance. These objects
66 implement the Node.js [`EventEmitter`][] API, allowing the parent process to
67 register listener functions that are called when certain events occur during
68 the life cycle of the child process.
69
70 The `child_process.exec()` and `child_process.execFile()` methods additionally
71 allow for an optional `callback` function to be specified that is invoked
72 when the child process terminates.
73
74 ### Spawning `.bat` and `.cmd` files on Windows
75
76 The importance of the distinction between `child_process.exec()` and
77 `child_process.execFile()` can vary based on platform. On Unix-type operating
78 systems (Unix, Linux, OSX) `child_process.execFile()` can be more efficient
79 because it does not spawn a shell. On Windows, however, `.bat` and `.cmd`
80 files are not executable on their own without a terminal and therefore cannot
81 be launched using `child_process.execFile()` (or even `child_process.spawn()`).
82 When running on Windows, `.bat` and `.cmd` files can only be invoked using
83 either `child_process.exec()` or by spawning `cmd.exe` and passing the `.bat`
84 or `.cmd` file as an argument (which is what `child_process.exec()` does).
85
86 ```js
87 // On Windows Only ...
88 const spawn = require('child_process').spawn;
89 const bat = spawn('cmd.exe', ['/c', 'my.bat']);
90
91 bat.stdout.on('data', (data) => {
92   console.log(data);
93 });
94
95 bat.stderr.on('data', (data) => {
96   console.log(data);
97 });
98
99 bat.on('exit', (code) => {
100   console.log(`Child exited with code ${code}`);
101 });
102
103 // OR...
104 const exec = require('child_process').exec;
105 exec('my.bat', (err, stdout, stderr) => {
106   if (err) {
107     console.error(err);
108     return;
109   }
110   console.log(stdout);
111 });
112 ```
113
114 ### child_process.exec(command[, options][, callback])
115
116 * `command` {String} The command to run, with space-separated arguments
117 * `options` {Object}
118   * `cwd` {String} Current working directory of the child process
119   * `env` {Object} Environment key-value pairs
120   * `encoding` {String} (Default: 'utf8')
121   * `shell` {String} Shell to execute the command with
122     (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows,  The shell should
123      understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows,
124      command line parsing should be compatible with `cmd.exe`.)
125   * `timeout` {Number} (Default: 0)
126   * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
127     stderr - if exceeded child process is killed (Default: `200*1024`)
128   * `killSignal` {String} (Default: 'SIGTERM')
129   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
130   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
131 * `callback` {Function} called with the output when process terminates
132   * `error` {Error}
133   * `stdout` {String|Buffer}
134   * `stderr` {String|Buffer}
135 * Return: {ChildProcess}
136
137 Spawns a shell then executes the `command` within that shell, buffering any
138 generated output.
139
140 ```js
141 const exec = require('child_process').exec;
142 const child = exec('cat *.js bad_file | wc -l',
143   (error, stdout, stderr) => {
144     console.log(`stdout: ${stdout}`);
145     console.log(`stderr: ${stderr}`);
146     if (error !== null) {
147       console.log(`exec error: ${error}`);
148     }
149 });
150 ```
151
152 If a `callback` function is provided, it is called with the arguments
153 `(error, stdout, stderr)`. On success, `error` will be `null`.  On error,
154 `error` will be an instance of [`Error`][]. The `error.code` property will be
155 the exit code of the child process while `error.signal` will be set to the
156 signal that terminated the process. Any exit code other than `0` is considered
157 to be an error.
158
159 The `stdout` and `stderr` arguments passed to the callback will contain the
160 stdout and stderr output of the child process. By default, Node.js will decode
161 the output as UTF-8 and pass strings to the callback. The `encoding` option
162 can be used to specify the character encoding used to decode the stdout and
163 stderr output. If `encoding` is `'buffer'`, `Buffer` objects will be passed to
164 the callback instead.
165
166 The `options` argument may be passed as the second argument to customize how
167 the process is spawned. The default options are:
168
169 ```js
170 {
171   encoding: 'utf8',
172   timeout: 0,
173   maxBuffer: 200*1024,
174   killSignal: 'SIGTERM',
175   cwd: null,
176   env: null
177 }
178 ```
179
180 If `timeout` is greater than `0`, the parent will send the the signal
181 identified by the `killSignal` property (the default is `'SIGTERM'`) if the
182 child runs longer than `timeout` milliseconds.
183
184 The `maxBuffer` option specifies the largest amount of data (in bytes) allowed
185 on stdout or stderr - if this value is exceeded then the child process is
186 terminated.
187
188 *Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not
189 replace the existing process and uses a shell to execute the command.*
190
191 ### child_process.execFile(file[, args][, options][, callback])
192
193 * `file` {String} The name or path of the executable file to run
194 * `args` {Array} List of string arguments
195 * `options` {Object}
196   * `cwd` {String} Current working directory of the child process
197   * `env` {Object} Environment key-value pairs
198   * `encoding` {String} (Default: 'utf8')
199   * `timeout` {Number} (Default: 0)
200   * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
201     stderr - if exceeded child process is killed (Default: 200\*1024)
202   * `killSignal` {String} (Default: 'SIGTERM')
203   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
204   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
205 * `callback` {Function} called with the output when process terminates
206   * `error` {Error}
207   * `stdout` {String|Buffer}
208   * `stderr` {String|Buffer}
209 * Return: {ChildProcess}
210
211 The `child_process.execFile()` function is similar to [`child_process.exec()`][]
212 except that it does not spawn a shell. Rather, the specified executable `file`
213 is spawned directly as a new process making it slightly more efficient than
214 [`child_process.exec()`][].
215
216 The same options as `child_process.exec()` are supported. Since a shell is not
217 spawned, behaviors such as I/O redirection and file globbing are not supported.
218
219 ```js
220 const execFile = require('child_process').execFile;
221 const child = execFile('node', ['--version'], (error, stdout, stderr) => {
222   if (error) {
223     throw error;
224   }
225   console.log(stdout);
226 });
227 ```
228
229 The `stdout` and `stderr` arguments passed to the callback will contain the
230 stdout and stderr output of the child process. By default, Node.js will decode
231 the output as UTF-8 and pass strings to the callback. The `encoding` option
232 can be used to specify the character encoding used to decode the stdout and
233 stderr output. If `encoding` is `'buffer'`, `Buffer` objects will be passed to
234 the callback instead.
235
236 ### child_process.fork(modulePath[, args][, options])
237
238 * `modulePath` {String} The module to run in the child
239 * `args` {Array} List of string arguments
240 * `options` {Object}
241   * `cwd` {String} Current working directory of the child process
242   * `env` {Object} Environment key-value pairs
243   * `execPath` {String} Executable used to create the child process
244   * `execArgv` {Array} List of string arguments passed to the executable
245     (Default: `process.execArgv`)
246   * `silent` {Boolean} If true, stdin, stdout, and stderr of the child will be
247     piped to the parent, otherwise they will be inherited from the parent, see
248     the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s
249     [`stdio`][] for more details (default is false)
250   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
251   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
252 * Return: {ChildProcess}
253
254 The `child_process.fork()` method is a special case of
255 [`child_process.spawn()`][] used specifically to spawn new Node.js processes.
256 Like `child_process.spawn()`, a `ChildProcess` object is returned. The returned
257 `ChildProcess` will have an additional communication channel built-in that
258 allows messages to be passed back and forth between the parent and child. See
259 [`ChildProcess#send()`][] for details.
260
261 It is important to keep in mind that spawned Node.js child processes are
262 independent of the parent with exception of the IPC communication channel
263 that is established between the two. Each process has it's own memory, with
264 their own V8 instances. Because of the additional resource allocations
265 required, spawning a large number of child Node.js processes is not
266 recommended.
267
268 By default, `child_process.fork()` will spawn new Node.js instances using the
269 `process.execPath` of the parent process. The `execPath` property in the
270 `options` object allows for an alternative execution path to be used.
271
272 Node.js processes launched with a custom `execPath` will communicate with the
273 parent process using the file descriptor (fd) identified using the
274 environment variable `NODE_CHANNEL_FD` on the child process. The input and
275 output on this fd is expected to be line delimited JSON objects.
276
277 *Note: Unlike the `fork()` POSIX system call, [`child_process.fork()`][] does
278 not clone the current process.*
279
280 ### child_process.spawn(command[, args][, options])
281
282 * `command` {String} The command to run
283 * `args` {Array} List of string arguments
284 * `options` {Object}
285   * `cwd` {String} Current working directory of the child process
286   * `env` {Object} Environment key-value pairs
287   * `stdio` {Array|String} Child's stdio configuration. (See
288     [`options.stdio`][])
289   * `detached` {Boolean} Prepare child to run independently of its parent
290     process. Specific behavior depends on the platform, see
291     [`options.detached`][])
292   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
293   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
294 * return: {ChildProcess}
295
296 The `child_process.spawn()` method spawns a new process using the given
297 `command`, with command line arguments in `args`. If omitted, `args` defaults
298 to an empty array.
299
300 A third argument may be used to specify additional options, with these defaults:
301
302 ```js
303 {
304   cwd: undefined,
305   env: process.env
306 }
307 ```
308
309 Use `cwd` to specify the working directory from which the process is spawned.
310 If not given, the default is to inherit the current working directory.
311
312 Use `env` to specify environment variables that will be visible to the new
313 process, the default is `process.env`.
314
315 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
316 exit code:
317
318 ```js
319 const spawn = require('child_process').spawn;
320 const ls = spawn('ls', ['-lh', '/usr']);
321
322 ls.stdout.on('data', (data) => {
323   console.log(`stdout: ${data}`);
324 });
325
326 ls.stderr.on('data', (data) => {
327   console.log(`stderr: ${data}`);
328 });
329
330 ls.on('close', (code) => {
331   console.log(`child process exited with code ${code}`);
332 });
333 ```
334
335
336 Example: A very elaborate way to run 'ps ax | grep ssh'
337
338 ```js
339 const spawn = require('child_process').spawn;
340 const ps = spawn('ps', ['ax']);
341 const grep = spawn('grep', ['ssh']);
342
343 ps.stdout.on('data', (data) => {
344   grep.stdin.write(data);
345 });
346
347 ps.stderr.on('data', (data) => {
348   console.log(`ps stderr: ${data}`);
349 });
350
351 ps.on('close', (code) => {
352   if (code !== 0) {
353     console.log(`ps process exited with code ${code}`);
354   }
355   grep.stdin.end();
356 });
357
358 grep.stdout.on('data', (data) => {
359   console.log(`${data}`);
360 });
361
362 grep.stderr.on('data', (data) => {
363   console.log(`grep stderr: ${data}`);
364 });
365
366 grep.on('close', (code) => {
367   if (code !== 0) {
368     console.log(`grep process exited with code ${code}`);
369   }
370 });
371 ```
372
373
374 Example of checking for failed exec:
375
376 ```js
377 const spawn = require('child_process').spawn;
378 const child = spawn('bad_command');
379
380 child.on('error', (err) => {
381   console.log('Failed to start child process.');
382 });
383 ```
384
385 #### options.detached
386
387 On Windows, setting `options.detached` to `true` makes it possible for the
388 child process to continue running after the parent exits. The child will have
389 its own console window. *Once enabled for a child process, it cannot be
390 disabled*.
391
392 On non-Windows platforms, if `options.detached` is set to `true`, the child
393 process will be made the leader of a new process group and session. Note that
394 child processes may continue running after the parent exits regardless of
395 whether they are detached or not.  See `setsid(2)` for more information.
396
397 By default, the parent will wait for the detached child to exit. To prevent
398 the parent from waiting for a given `child`, use the `child.unref()` method.
399 Doing so will cause the parent's event loop to not include the child in its
400 reference count, allowing the parent to exit independently of the child, unless
401 there is an established IPC channel between the child and parent.
402
403 When using the `detached` option to start a long-running process, the process
404 will not stay running in the background after the parent exits unless it is
405 provided with a `stdio` configuration that is not connected to the parent.
406 If the parent's `stdio` is inherited, the child will remain attached to the
407 controlling terminal.
408
409 Example of a long-running process, by detaching and also ignoring its parent
410 `stdio` file descriptors, in order to ignore the parent's termination:
411
412 ```js
413 const spawn = require('child_process').spawn;
414
415 const child = spawn(process.argv[0], ['child_program.js'], {
416   detached: true,
417   stdio: ['ignore']
418 });
419
420 child.unref();
421 ```
422
423 Alternatively one can redirect the child process' output into files:
424
425 ```js
426 const fs = require('fs');
427 const spawn = require('child_process').spawn;
428 const out = fs.openSync('./out.log', 'a');
429 const err = fs.openSync('./out.log', 'a');
430
431 const child = spawn('prg', [], {
432  detached: true,
433  stdio: [ 'ignore', out, err ]
434 });
435
436 child.unref();
437 ```
438
439 #### options.stdio
440
441 The `options.stdio` option is used to configure the pipes that are established
442 between the parent and child process. By default, the child's stdin, stdout,
443 and stderr are redirected to corresponding `child.stdin`, `child.stdout`, and
444 `child.stderr` streams on the `ChildProcess` object. This is equivalent to
445 setting the `options.stdio` equal to `['pipe', 'pipe', 'pipe']`.
446
447 For convenience, `options.stdio` may be one of the following strings:
448
449 * `'pipe'` - equivalent to `['pipe', 'pipe', 'pipe']` (the default)
450 * `'ignore'` - equivalent to `['ignore', 'ignore', 'ignore']`
451 * `'inherit'` - equivalent to `[process.stdin, process.stdout, process.stderr]`
452    or `[0,1,2]`
453
454 Otherwise, the value of `option.stdio` is an array where each index corresponds
455 to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
456 and stderr, respectively. Additional fds can be specified to create additional
457 pipes between the parent and child. The value is one of the following:
458
459 1. `'pipe'` - Create a pipe between the child process and the parent process.
460    The parent end of the pipe is exposed to the parent as a property on the
461    `child_process` object as `ChildProcess.stdio[fd]`. Pipes created for
462    fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
463    and ChildProcess.stderr, respectively.
464 2. `'ipc'` - Create an IPC channel for passing messages/file descriptors
465    between parent and child. A ChildProcess may have at most *one* IPC stdio
466    file descriptor. Setting this option enables the ChildProcess.send() method.
467    If the child writes JSON messages to this file descriptor, the
468    `ChildProcess.on('message')` event handler will be triggered in the parent.
469    If the child is a Node.js process, the presence of an IPC channel will enable
470    `process.send()`, `process.disconnect()`, `process.on('disconnect')`, and
471    `process.on('message')` within the child.
472 3. `'ignore'` - Instructs Node.js to ignore the fd in the child. While Node.js
473    will always open fds 0 - 2 for the processes it spawns, setting the fd to
474    `'ignore'` will cause Node.js to open `/dev/null` and attach it to the
475    child's fd.
476 4. `Stream` object - Share a readable or writable stream that refers to a tty,
477    file, socket, or a pipe with the child process. The stream's underlying
478    file descriptor is duplicated in the child process to the fd that
479    corresponds to the index in the `stdio` array. Note that the stream must
480    have an underlying descriptor (file streams do not until the `'open'`
481    event has occurred).
482 5. Positive integer - The integer value is interpreted as a file descriptor
483    that is is currently open in the parent process. It is shared with the child
484    process, similar to how `Stream` objects can be shared.
485 6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
486    words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
487    default is `'ignore'`.
488
489 Example:
490
491 ```js
492 const spawn = require('child_process').spawn;
493
494 // Child will use parent's stdios
495 spawn('prg', [], { stdio: 'inherit' });
496
497 // Spawn child sharing only stderr
498 spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
499
500 // Open an extra fd=4, to interact with programs presenting a
501 // startd-style interface.
502 spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
503 ```
504
505 *It is worth noting that when an IPC channel is established between the
506 parent and child processes, and the child is a Node.js process, the child
507 is launched with the IPC channel unreferenced (using `unref()`) until the
508 child registers an event handler for the `process.on('disconnected')` event.
509 This allows the child to exit normally without the process being held open
510 by the open IPC channel.*
511
512 See also: [`child_process.exec()`][] and [`child_process.fork()`][]
513
514 ## Synchronous Process Creation
515
516 The `child_process.spawnSync()`, `child_process.execSync()`, and
517 `child_process.execFileSync()` methods are **synchronous** and **WILL** block
518 the Node.js event loop, pausing execution of any additional code until the
519 spawned process exits.
520
521 Blocking calls like these are mostly useful for simplifying general purpose
522 scripting tasks and for simplifying the loading/processing of application
523 configuration at startup.
524
525 ### child_process.execFileSync(file[, args][, options])
526
527 * `file` {String} The name or path of the executable file to run
528 * `args` {Array} List of string arguments
529 * `options` {Object}
530   * `cwd` {String} Current working directory of the child process
531   * `input` {String|Buffer} The value which will be passed as stdin to the spawned process
532     - supplying this value will override `stdio[0]`
533   * `stdio` {Array} Child's stdio configuration. (Default: 'pipe')
534     - `stderr` by default will be output to the parent process' stderr unless
535       `stdio` is specified
536   * `env` {Object} Environment key-value pairs
537   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
538   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
539   * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)
540   * `killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')
541   * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
542     stderr - if exceeded child process is killed
543   * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
544 * return: {Buffer|String} The stdout from the command
545
546 The `child_process.execFileSync()` method is generally identical to
547 `child_process.execFile()` with the exception that the method will not return
548 until the child process has fully closed. When a timeout has been encountered
549 and `killSignal` is sent, the method won't return until the process has
550 completely exited. *Note that if the child process intercepts and handles
551 the `SIGTERM` signal and does not exit, the parent process will still wait
552 until the child process has exited.*
553
554 If the process times out, or has a non-zero exit code, this method ***will***
555 throw.  The [`Error`][] object will contain the entire result from
556 [`child_process.spawnSync()`][]
557
558 ### child_process.execSync(command[, options])
559
560 * `command` {String} The command to run
561 * `options` {Object}
562   * `cwd` {String} Current working directory of the child process
563   * `input` {String|Buffer} The value which will be passed as stdin to the spawned process
564     - supplying this value will override `stdio[0]`
565   * `stdio` {Array} Child's stdio configuration. (Default: 'pipe')
566     - `stderr` by default will be output to the parent process' stderr unless
567       `stdio` is specified
568   * `env` {Object} Environment key-value pairs
569   * `shell` {String} Shell to execute the command with
570     (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows,  The shell should
571      understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows,
572      command line parsing should be compatible with `cmd.exe`.)
573   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
574   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
575   * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)
576   * `killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')
577   * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
578     stderr - if exceeded child process is killed
579   * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
580 * return: {Buffer|String} The stdout from the command
581
582 The `child_process.execSync()` method is generally identical to
583 `child_process.exec()` with the exception that the method will not return until
584 the child process has fully closed. When a timeout has been encountered and
585 `killSignal` is sent, the method won't return until the process has completely
586 exited. *Note that if  the child process intercepts and handles the `SIGTERM`
587 signal and doesn't exit, the parent process will wait until the child
588 process has exited.*
589
590 If the process times out, or has a non-zero exit code, this method ***will***
591 throw.  The [`Error`][] object will contain the entire result from
592 [`child_process.spawnSync()`][]
593
594 ### child_process.spawnSync(command[, args][, options])
595
596 * `command` {String} The command to run
597 * `args` {Array} List of string arguments
598 * `options` {Object}
599   * `cwd` {String} Current working directory of the child process
600   * `input` {String|Buffer} The value which will be passed as stdin to the spawned process
601     - supplying this value will override `stdio[0]`
602   * `stdio` {Array} Child's stdio configuration.
603   * `env` {Object} Environment key-value pairs
604   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
605   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
606   * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: undefined)
607   * `killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')
608   * `maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or
609     stderr - if exceeded child process is killed
610   * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
611 * return: {Object}
612   * `pid` {Number} Pid of the child process
613   * `output` {Array} Array of results from stdio output
614   * `stdout` {Buffer|String} The contents of `output[1]`
615   * `stderr` {Buffer|String} The contents of `output[2]`
616   * `status` {Number} The exit code of the child process
617   * `signal` {String} The signal used to kill the child process
618   * `error` {Error} The error object if the child process failed or timed out
619
620 The `child_process.spawnSync()` method is generally identical to
621 `child_process.spawn()` with the exception that the function will not return
622 until the child process has fully closed. When a timeout has been encountered
623 and `killSignal` is sent, the method won't return until the process has
624 completely exited. Note that if the process intercepts and handles the
625 `SIGTERM` signal and doesn't exit, the parent process will wait until the child
626 process has exited.
627
628 ## Class: ChildProcess
629
630 Instances of the `ChildProcess` class are [`EventEmitters`][] that represent
631 spawned child processes.
632
633 Instances of `ChildProcess` are not intended to be created directly. Rather,
634 use the [`child_process.spawn()`][], [`child_process.exec()`][],
635 [`child_process.execFile()`][], or [`child_process.fork()`][] methods to create
636 instances of `ChildProcess`.
637
638 ### Event: 'close'
639
640 * `code` {Number} the exit code if the child exited on its own.
641 * `signal` {String} the signal by which the child process was terminated.
642
643 The `'close'` event is emitted when the stdio streams of a child process have
644 been closed. This is distinct from the `'exit'` event, since multiple
645 processes might share the same stdio streams.
646
647 ### Event: 'disconnect'
648
649 The `'disconnect'` event is emitted after calling the
650 `ChildProcess.disconnect()` method in the parent or child process. After
651 disconnecting it is no longer possible to send or receive messages, and the
652 `ChildProcess.connected` property is false.
653
654 ### Event:  'error'
655
656 * `err` {Error} the error.
657
658 The `'error'` event is emitted whenever:
659
660 1. The process could not be spawned, or
661 2. The process could not be killed, or
662 3. Sending a message to the child process failed.
663
664 Note that the `'exit'` event may or may not fire after an error has occurred.
665 If you are listening to both the `'exit'` and `'error'` events, it is important
666 to guard against accidentally invoking handler functions multiple times.
667
668 See also [`ChildProcess#kill()`][] and [`ChildProcess#send()`][].
669
670 ### Event:  'exit'
671
672 * `code` {Number} the exit code if the child exited on its own.
673 * `signal` {String} the signal by which the child process was terminated.
674
675 The `'exit'` event is emitted after the child process ends. If the process
676 exited, `code` is the final exit code of the process, otherwise `null`. If the
677 process terminated due to receipt of a signal, `signal` is the string name of
678 the signal, otherwise `null`. One of the two will always be non-null.
679
680 Note that when the `'exit'` event is triggered, child process stdio streams
681 might still be open.
682
683 Also, note that Node.js establishes signal handlers for `SIGINT` and
684 `SIGTERM` and Node.js processes will not terminate immediately due to receipt
685 of those signals. Rather, Node.js will perform a sequence of cleanup actions
686 and then will re-raise the handled signal.
687
688 See `waitpid(2)`.
689
690 ### Event: 'message'
691
692 * `message` {Object} a parsed JSON object or primitive value.
693 * `sendHandle` {Handle} a [`net.Socket`][] or [`net.Server`][] object, or
694   undefined.
695
696 The `'message'` event is triggered when a child process uses `process.send()`
697 to send messages.
698
699 ### child.connected
700
701 * {Boolean} Set to false after `.disconnect` is called
702
703 The `child.connected` property indicates whether it is still possible to send
704 and receive messages from a child process. When `child.connected` is false, it
705 is no longer possible to send or receive messages.
706
707 ### child.disconnect()
708
709 Closes the IPC channel between parent and child, allowing the child to exit
710 gracefully once there are no other connections keeping it alive. After calling
711 this method the `child.connected` and `process.connected` properties in both
712 the parent and child (respectively) will be set to `false`, and it will be no
713 longer possible to pass messages between the processes.
714
715 The `'disconnect'` event will be emitted when there are no messages in the
716 process of being received. This will most often be triggered immediately after
717 calling `child.disconnect()`.
718
719 Note that when the child process is a Node.js instance (e.g. spawned using
720 [`child_process.fork()`]), the `process.disconnect()` method can be invoked
721 within the child process to close the IPC channel as well.
722
723 ### child.kill([signal])
724
725 * `signal` {String}
726
727 The `child.kill()` methods sends a signal to the child process. If no argument
728 is given, the process will be sent the `'SIGTERM'` signal. See `signal(7)` for
729 a list of available signals.
730
731 ```js
732 const spawn = require('child_process').spawn;
733 const grep = spawn('grep', ['ssh']);
734
735 grep.on('close', (code, signal) => {
736   console.log(
737     `child process terminated due to receipt of signal ${signal}`);
738 });
739
740 // Send SIGHUP to process
741 grep.kill('SIGHUP');
742 ```
743
744 The `ChildProcess` object may emit an `'error'` event if the signal cannot be
745 delivered. Sending a signal to a child process that has already exited is not
746 an error but may have unforeseen consequences. Specifically, if the process
747 identifier (PID) has been reassigned to another process, the signal will be
748 delivered to that process instead which can have unexpected results.
749
750 Note that while the function is called `kill`, the signal delivered to the
751 child process may not actually terminate the process.
752
753 See `kill(2)`
754
755 ### child.pid
756
757 * {Number} Integer
758
759 Returns the process identifier (PID) of the child process.
760
761 Example:
762
763 ```js
764 const spawn = require('child_process').spawn;
765 const grep = spawn('grep', ['ssh']);
766
767 console.log(`Spawned child pid: ${grep.pid}`);
768 grep.stdin.end();
769 ```
770
771 ### child.send(message[, sendHandle][, callback])
772
773 * `message` {Object}
774 * `sendHandle` {Handle}
775 * `callback` {Function}
776 * Return: {Boolean}
777
778 When an IPC channel has been established between the parent and child (
779 i.e. when using [`child_process.fork()`][]), the `child.send()` method can be
780 used to send messages to the child process. When the child process is a Node.js
781 instance, these messages can be received via the `process.on('message')` event.
782
783 For example, in the parent script:
784
785 ```js
786 const cp = require('child_process');
787 const n = cp.fork(`${__dirname}/sub.js`);
788
789 n.on('message', (m) => {
790   console.log('PARENT got message:', m);
791 });
792
793 n.send({ hello: 'world' });
794 ```
795
796 And then the child script, `'sub.js'` might look like this:
797
798 ```js
799 process.on('message', (m) => {
800   console.log('CHILD got message:', m);
801 });
802
803 process.send({ foo: 'bar' });
804 ```
805
806 Child Node.js processes will have a `process.send()` method of their own that
807 allows the child to send messages back to the parent.
808
809 There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
810 containing a `NODE_` prefix in its `cmd` property are considered to be reserved
811 for use within Node.js core and will not be emitted in the child's
812 `process.on('message')` event. Rather, such messages are emitted using the
813 `process.on('internalMessage')` event and are consumed internally by Node.js.
814 Applications should avoid using such messages or listening for
815 `'internalMessage'` events as it is subject to change without notice.
816
817 The optional `sendHandle` argument that may be passed to `child.send()` is for
818 passing a TCP server or socket object to the child process. The child will
819 receive the object as the second argument passed to the callback function
820 registered on the `process.on('message')` event.
821
822 The optional `callback` is a function that is invoked after the message is
823 sent but before the child may have received it.  The function is called with a
824 single argument: `null` on success, or an [`Error`][] object on failure.
825
826 If no `callback` function is provided and the message cannot be sent, an
827 `'error'` event will be emitted by the `ChildProcess` object. This can happen,
828 for instance, when the child process has already exited.
829
830 `child.send()` will return `false` if the channel has closed or when the
831 backlog of unsent messages exceeds a threshold that makes it unwise to send
832 more. Otherwise, the method returns `true`. The `callback` function can be
833 used to implement flow control.
834
835 #### Example: sending a server object
836
837 The `sendHandle` argument can be used, for instance, to pass the handle of
838 a TCP server object to the child process as illustrated in the example below:
839
840 ```js
841 const child = require('child_process').fork('child.js');
842
843 // Open up the server object and send the handle.
844 const server = require('net').createServer();
845 server.on('connection', (socket) => {
846   socket.end('handled by parent');
847 });
848 server.listen(1337, () => {
849   child.send('server', server);
850 });
851 ```
852
853 The child would then receive the server object as:
854
855 ```js
856 process.on('message', (m, server) => {
857   if (m === 'server') {
858     server.on('connection', (socket) => {
859       socket.end('handled by child');
860     });
861   }
862 });
863 ```
864
865 Once the server is now shared between the parent and child, some connections
866 can be handled by the parent and some by the child.
867
868 While the example above uses a server created using the `net` module, `dgram`
869 module servers use exactly the same workflow with the exceptions of listening on
870 a `'message'` event instead of `'connection'` and using `server.bind` instead of
871 `server.listen`. This is, however, currently only supported on UNIX platforms.
872
873 #### Example: sending a socket object
874
875 Similarly, the `sendHandler` argument can be used to pass the handle of a
876 socket to the child process. The example below spawns two children that each
877 handle connections with "normal" or "special" priority:
878
879 ```js
880 const normal = require('child_process').fork('child.js', ['normal']);
881 const special = require('child_process').fork('child.js', ['special']);
882
883 // Open up the server and send sockets to child
884 const server = require('net').createServer();
885 server.on('connection', (socket) => {
886
887   // If this is special priority
888   if (socket.remoteAddress === '74.125.127.100') {
889     special.send('socket', socket);
890     return;
891   }
892   // This is normal priority
893   normal.send('socket', socket);
894 });
895 server.listen(1337);
896 ```
897
898 The `child.js` would receive the socket handle as the second argument passed
899 to the event callback function:
900
901 ```js
902 process.on('message', (m, socket) => {
903   if (m === 'socket') {
904     socket.end(`Request handled with ${process.argv[2]} priority`);
905   }
906 });
907 ```
908
909 Once a socket has been passed to a child, the parent is no longer capable of
910 tracking when the socket is destroyed. To indicate this, the `.connections`
911 property becomes `null`. It is recommended not to use `.maxConnections` when
912 this occurs.
913
914 *Note: this function uses [`JSON.stringify()`][] internally to serialize the `message`.*
915
916 ### child.stderr
917
918 * {Stream}
919
920 A `Readable Stream` that represents the child process's `stderr`.
921
922 If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
923 then this will be `undefined`.
924
925 `child.stderr` is an alias for `child.stdio[2]`. Both properties will refer to
926 the same value.
927
928 ### child.stdin
929
930 * {Stream}
931
932 A `Writable Stream` that represents the child process's `stdin`.
933
934 *Note that if a child process waits to read all of its input, the child will not
935 continue until this stream has been closed via `end()`.*
936
937 If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
938 then this will be `undefined`.
939
940 `child.stdin` is an alias for `child.stdio[0]`. Both properties will refer to
941 the same value.
942
943 ### child.stdio
944
945 * {Array}
946
947 A sparse array of pipes to the child process, corresponding with positions in
948 the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
949 to the value `'pipe'`. Note that `child.stdio[0]`, `child.stdio[1]`, and
950 `child.stdio[2]` are also available as `child.stdin`, `child.stdout`, and
951 `child.stderr`, respectively.
952
953 In the following example, only the child's fd `1` (stdout) is configured as a
954 pipe, so only the parent's `child.stdio[1]` is a stream, all other values in
955 the array are `null`.
956
957 ```js
958 const assert = require('assert');
959 const fs = require('fs');
960 const child_process = require('child_process');
961
962 const child = child_process.spawn('ls', {
963     stdio: [
964       0, // Use parents stdin for child
965       'pipe', // Pipe child's stdout to parent
966       fs.openSync('err.out', 'w') // Direct child's stderr to a file
967     ]
968 });
969
970 assert.equal(child.stdio[0], null);
971 assert.equal(child.stdio[0], child.stdin);
972
973 assert(child.stdout);
974 assert.equal(child.stdio[1], child.stdout);
975
976 assert.equal(child.stdio[2], null);
977 assert.equal(child.stdio[2], child.stderr);
978 ```
979
980 ### child.stdout
981
982 * {Stream}
983
984 A `Readable Stream` that represents the child process's `stdout`.
985
986 If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
987 then this will be `undefined`.
988
989 `child.stdout` is an alias for `child.stdio[1]`. Both properties will refer
990 to the same value.
991
992 [`popen(3)`]: http://linux.die.net/man/3/popen
993 [`ChildProcess`]: #child_process_child_process
994 [`child_process.exec()`]: #child_process_child_process_exec_command_options_callback
995 [`child_process.execFile()`]: #child_process_child_process_execfile_file_args_options_callback
996 [`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
997 [`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options
998 [`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options
999 [`ChildProcess#kill()`]: #child_process_child_kill_signal
1000 [`ChildProcess#send()`]: #child_process_child_send_message_sendhandle_callback
1001 [`Error`]: errors.html#errors_class_error
1002 [`EventEmitter`]: events.html#events_class_events_eventemitter
1003 [`EventEmitters`]: events.html#events_class_events_eventemitter
1004 [`net.Server`]: net.html#net_class_net_server
1005 [`net.Socket`]: net.html#net_class_net_socket
1006 [`options.detached`]: #child_process_options_detached
1007 [`options.stdio`]: #child_process_options_stdio
1008 [`stdio`]: #child_process_options_stdio
1009 [synchronous counterparts]: #child_process_synchronous_process_creation
1010 [`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify