• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Child process
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/child_process.js -->
8
9The `child_process` module provides the ability to spawn child processes in
10a manner that is similar, but not identical, to popen(3). This capability
11is primarily provided by the [`child_process.spawn()`][] function:
12
13```js
14const { spawn } = require('child_process');
15const ls = spawn('ls', ['-lh', '/usr']);
16
17ls.stdout.on('data', (data) => {
18  console.log(`stdout: ${data}`);
19});
20
21ls.stderr.on('data', (data) => {
22  console.error(`stderr: ${data}`);
23});
24
25ls.on('close', (code) => {
26  console.log(`child process exited with code ${code}`);
27});
28```
29
30By default, pipes for `stdin`, `stdout`, and `stderr` are established between
31the parent Node.js process and the spawned child. These pipes have
32limited (and platform-specific) capacity. If the child process writes to
33stdout in excess of that limit without the output being captured, the child
34process will block waiting for the pipe buffer to accept more data. This is
35identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`
36option if the output will not be consumed.
37
38The command lookup will be performed using `options.env.PATH` environment
39variable if passed in `options` object, otherwise `process.env.PATH` will be
40used. To account for the fact that Windows environment variables are
41case-insensitive Node.js will lexicographically sort all `env` keys and choose
42the first one case-insensitively matching `PATH` to perform command lookup.
43This may lead to issues on Windows when passing objects to `env` option that
44have multiple variants of `PATH` variable.
45
46The [`child_process.spawn()`][] method spawns the child process asynchronously,
47without blocking the Node.js event loop. The [`child_process.spawnSync()`][]
48function provides equivalent functionality in a synchronous manner that blocks
49the event loop until the spawned process either exits or is terminated.
50
51For convenience, the `child_process` module provides a handful of synchronous
52and asynchronous alternatives to [`child_process.spawn()`][] and
53[`child_process.spawnSync()`][]. Each of these alternatives are implemented on
54top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].
55
56* [`child_process.exec()`][]: spawns a shell and runs a command within that
57  shell, passing the `stdout` and `stderr` to a callback function when
58  complete.
59* [`child_process.execFile()`][]: similar to [`child_process.exec()`][] except
60  that it spawns the command directly without first spawning a shell by
61  default.
62* [`child_process.fork()`][]: spawns a new Node.js process and invokes a
63  specified module with an IPC communication channel established that allows
64  sending messages between parent and child.
65* [`child_process.execSync()`][]: a synchronous version of
66  [`child_process.exec()`][] that will block the Node.js event loop.
67* [`child_process.execFileSync()`][]: a synchronous version of
68  [`child_process.execFile()`][] that will block the Node.js event loop.
69
70For certain use cases, such as automating shell scripts, the
71[synchronous counterparts][] may be more convenient. In many cases, however,
72the synchronous methods can have significant impact on performance due to
73stalling the event loop while spawned processes complete.
74
75## Asynchronous process creation
76
77The [`child_process.spawn()`][], [`child_process.fork()`][], [`child_process.exec()`][],
78and [`child_process.execFile()`][] methods all follow the idiomatic asynchronous
79programming pattern typical of other Node.js APIs.
80
81Each of the methods returns a [`ChildProcess`][] instance. These objects
82implement the Node.js [`EventEmitter`][] API, allowing the parent process to
83register listener functions that are called when certain events occur during
84the life cycle of the child process.
85
86The [`child_process.exec()`][] and [`child_process.execFile()`][] methods
87additionally allow for an optional `callback` function to be specified that is
88invoked when the child process terminates.
89
90### Spawning `.bat` and `.cmd` files on Windows
91
92The importance of the distinction between [`child_process.exec()`][] and
93[`child_process.execFile()`][] can vary based on platform. On Unix-type
94operating systems (Unix, Linux, macOS) [`child_process.execFile()`][] can be
95more efficient because it does not spawn a shell by default. On Windows,
96however, `.bat` and `.cmd` files are not executable on their own without a
97terminal, and therefore cannot be launched using [`child_process.execFile()`][].
98When running on Windows, `.bat` and `.cmd` files can be invoked using
99[`child_process.spawn()`][] with the `shell` option set, with
100[`child_process.exec()`][], or by spawning `cmd.exe` and passing the `.bat` or
101`.cmd` file as an argument (which is what the `shell` option and
102[`child_process.exec()`][] do). In any case, if the script filename contains
103spaces it needs to be quoted.
104
105```js
106// On Windows Only...
107const { spawn } = require('child_process');
108const bat = spawn('cmd.exe', ['/c', 'my.bat']);
109
110bat.stdout.on('data', (data) => {
111  console.log(data.toString());
112});
113
114bat.stderr.on('data', (data) => {
115  console.error(data.toString());
116});
117
118bat.on('exit', (code) => {
119  console.log(`Child exited with code ${code}`);
120});
121```
122
123```js
124// OR...
125const { exec, spawn } = require('child_process');
126exec('my.bat', (err, stdout, stderr) => {
127  if (err) {
128    console.error(err);
129    return;
130  }
131  console.log(stdout);
132});
133
134// Script with spaces in the filename:
135const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
136// or:
137exec('"my script.cmd" a b', (err, stdout, stderr) => {
138  // ...
139});
140```
141
142### `child_process.exec(command[, options][, callback])`
143<!-- YAML
144added: v0.1.90
145changes:
146  - version: v8.8.0
147    pr-url: https://github.com/nodejs/node/pull/15380
148    description: The `windowsHide` option is supported now.
149-->
150
151* `command` {string} The command to run, with space-separated arguments.
152* `options` {Object}
153  * `cwd` {string} Current working directory of the child process.
154    **Default:** `null`.
155  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
156  * `encoding` {string} **Default:** `'utf8'`
157  * `shell` {string} Shell to execute the command with. See
158    [Shell requirements][] and [Default Windows shell][]. **Default:**
159    `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.
160  * `timeout` {number} **Default:** `0`
161  * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
162    stderr. If exceeded, the child process is terminated and any output is
163    truncated. See caveat at [`maxBuffer` and Unicode][].
164    **Default:** `1024 * 1024`.
165  * `killSignal` {string|integer} **Default:** `'SIGTERM'`
166  * `uid` {number} Sets the user identity of the process (see setuid(2)).
167  * `gid` {number} Sets the group identity of the process (see setgid(2)).
168  * `windowsHide` {boolean} Hide the subprocess console window that would
169    normally be created on Windows systems. **Default:** `false`.
170* `callback` {Function} called with the output when process terminates.
171  * `error` {Error}
172  * `stdout` {string|Buffer}
173  * `stderr` {string|Buffer}
174* Returns: {ChildProcess}
175
176Spawns a shell then executes the `command` within that shell, buffering any
177generated output. The `command` string passed to the exec function is processed
178directly by the shell and special characters (vary based on
179[shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
180need to be dealt with accordingly:
181
182```js
183exec('"/path/to/test file/test.sh" arg1 arg2');
184// Double quotes are used so that the space in the path is not interpreted as
185// a delimiter of multiple arguments.
186
187exec('echo "The \\$HOME variable is $HOME"');
188// The $HOME variable is escaped in the first instance, but not in the second.
189```
190
191**Never pass unsanitized user input to this function. Any input containing shell
192metacharacters may be used to trigger arbitrary command execution.**
193
194If a `callback` function is provided, it is called with the arguments
195`(error, stdout, stderr)`. On success, `error` will be `null`. On error,
196`error` will be an instance of [`Error`][]. The `error.code` property will be
197the exit code of the process. By convention, any exit code other than `0`
198indicates an error. `error.signal` will be the signal that terminated the
199process.
200
201The `stdout` and `stderr` arguments passed to the callback will contain the
202stdout and stderr output of the child process. By default, Node.js will decode
203the output as UTF-8 and pass strings to the callback. The `encoding` option
204can be used to specify the character encoding used to decode the stdout and
205stderr output. If `encoding` is `'buffer'`, or an unrecognized character
206encoding, `Buffer` objects will be passed to the callback instead.
207
208```js
209const { exec } = require('child_process');
210exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
211  if (error) {
212    console.error(`exec error: ${error}`);
213    return;
214  }
215  console.log(`stdout: ${stdout}`);
216  console.error(`stderr: ${stderr}`);
217});
218```
219
220If `timeout` is greater than `0`, the parent will send the signal
221identified by the `killSignal` property (the default is `'SIGTERM'`) if the
222child runs longer than `timeout` milliseconds.
223
224Unlike the exec(3) POSIX system call, `child_process.exec()` does not replace
225the existing process and uses a shell to execute the command.
226
227If this method is invoked as its [`util.promisify()`][]ed version, it returns
228a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned
229`ChildProcess` instance is attached to the `Promise` as a `child` property. In
230case of an error (including any error resulting in an exit code other than 0), a
231rejected promise is returned, with the same `error` object given in the
232callback, but with two additional properties `stdout` and `stderr`.
233
234```js
235const util = require('util');
236const exec = util.promisify(require('child_process').exec);
237
238async function lsExample() {
239  const { stdout, stderr } = await exec('ls');
240  console.log('stdout:', stdout);
241  console.error('stderr:', stderr);
242}
243lsExample();
244```
245
246### `child_process.execFile(file[, args][, options][, callback])`
247<!-- YAML
248added: v0.1.91
249changes:
250  - version: v8.8.0
251    pr-url: https://github.com/nodejs/node/pull/15380
252    description: The `windowsHide` option is supported now.
253-->
254
255* `file` {string} The name or path of the executable file to run.
256* `args` {string[]} List of string arguments.
257* `options` {Object}
258  * `cwd` {string} Current working directory of the child process.
259  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
260  * `encoding` {string} **Default:** `'utf8'`
261  * `timeout` {number} **Default:** `0`
262  * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
263    stderr. If exceeded, the child process is terminated and any output is
264    truncated. See caveat at [`maxBuffer` and Unicode][].
265    **Default:** `1024 * 1024`.
266  * `killSignal` {string|integer} **Default:** `'SIGTERM'`
267  * `uid` {number} Sets the user identity of the process (see setuid(2)).
268  * `gid` {number} Sets the group identity of the process (see setgid(2)).
269  * `windowsHide` {boolean} Hide the subprocess console window that would
270    normally be created on Windows systems. **Default:** `false`.
271  * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
272    done on Windows. Ignored on Unix. **Default:** `false`.
273  * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
274    `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
275    shell can be specified as a string. See [Shell requirements][] and
276    [Default Windows shell][]. **Default:** `false` (no shell).
277* `callback` {Function} Called with the output when process terminates.
278  * `error` {Error}
279  * `stdout` {string|Buffer}
280  * `stderr` {string|Buffer}
281* Returns: {ChildProcess}
282
283The `child_process.execFile()` function is similar to [`child_process.exec()`][]
284except that it does not spawn a shell by default. Rather, the specified
285executable `file` is spawned directly as a new process making it slightly more
286efficient than [`child_process.exec()`][].
287
288The same options as [`child_process.exec()`][] are supported. Since a shell is
289not spawned, behaviors such as I/O redirection and file globbing are not
290supported.
291
292```js
293const { execFile } = require('child_process');
294const child = execFile('node', ['--version'], (error, stdout, stderr) => {
295  if (error) {
296    throw error;
297  }
298  console.log(stdout);
299});
300```
301
302The `stdout` and `stderr` arguments passed to the callback will contain the
303stdout and stderr output of the child process. By default, Node.js will decode
304the output as UTF-8 and pass strings to the callback. The `encoding` option
305can be used to specify the character encoding used to decode the stdout and
306stderr output. If `encoding` is `'buffer'`, or an unrecognized character
307encoding, `Buffer` objects will be passed to the callback instead.
308
309If this method is invoked as its [`util.promisify()`][]ed version, it returns
310a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned
311`ChildProcess` instance is attached to the `Promise` as a `child` property. In
312case of an error (including any error resulting in an exit code other than 0), a
313rejected promise is returned, with the same `error` object given in the
314callback, but with two additional properties `stdout` and `stderr`.
315
316```js
317const util = require('util');
318const execFile = util.promisify(require('child_process').execFile);
319async function getVersion() {
320  const { stdout } = await execFile('node', ['--version']);
321  console.log(stdout);
322}
323getVersion();
324```
325
326**If the `shell` option is enabled, do not pass unsanitized user input to this
327function. Any input containing shell metacharacters may be used to trigger
328arbitrary command execution.**
329
330### `child_process.fork(modulePath[, args][, options])`
331<!-- YAML
332added: v0.5.0
333changes:
334  - version: v12.16.0
335    pr-url: https://github.com/nodejs/node/pull/30162
336    description: The `serialization` option is supported now.
337  - version: v8.0.0
338    pr-url: https://github.com/nodejs/node/pull/10866
339    description: The `stdio` option can now be a string.
340  - version: v6.4.0
341    pr-url: https://github.com/nodejs/node/pull/7811
342    description: The `stdio` option is supported now.
343-->
344
345* `modulePath` {string} The module to run in the child.
346* `args` {string[]} List of string arguments.
347* `options` {Object}
348  * `cwd` {string} Current working directory of the child process.
349  * `detached` {boolean} Prepare child to run independently of its parent
350    process. Specific behavior depends on the platform, see
351    [`options.detached`][]).
352  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
353  * `execPath` {string} Executable used to create the child process.
354  * `execArgv` {string[]} List of string arguments passed to the executable.
355    **Default:** `process.execArgv`.
356  * `serialization` {string} Specify the kind of serialization used for sending
357    messages between processes. Possible values are `'json'` and `'advanced'`.
358    See [Advanced serialization][] for more details. **Default:** `'json'`.
359  * `silent` {boolean} If `true`, stdin, stdout, and stderr of the child will be
360    piped to the parent, otherwise they will be inherited from the parent, see
361    the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s
362    [`stdio`][] for more details. **Default:** `false`.
363  * `stdio` {Array|string} See [`child_process.spawn()`][]'s [`stdio`][].
364    When this option is provided, it overrides `silent`. If the array variant
365    is used, it must contain exactly one item with value `'ipc'` or an error
366    will be thrown. For instance `[0, 1, 2, 'ipc']`.
367  * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
368    done on Windows. Ignored on Unix. **Default:** `false`.
369  * `uid` {number} Sets the user identity of the process (see setuid(2)).
370  * `gid` {number} Sets the group identity of the process (see setgid(2)).
371* Returns: {ChildProcess}
372
373The `child_process.fork()` method is a special case of
374[`child_process.spawn()`][] used specifically to spawn new Node.js processes.
375Like [`child_process.spawn()`][], a [`ChildProcess`][] object is returned. The
376returned [`ChildProcess`][] will have an additional communication channel
377built-in that allows messages to be passed back and forth between the parent and
378child. See [`subprocess.send()`][] for details.
379
380Keep in mind that spawned Node.js child processes are
381independent of the parent with exception of the IPC communication channel
382that is established between the two. Each process has its own memory, with
383their own V8 instances. Because of the additional resource allocations
384required, spawning a large number of child Node.js processes is not
385recommended.
386
387By default, `child_process.fork()` will spawn new Node.js instances using the
388[`process.execPath`][] of the parent process. The `execPath` property in the
389`options` object allows for an alternative execution path to be used.
390
391Node.js processes launched with a custom `execPath` will communicate with the
392parent process using the file descriptor (fd) identified using the
393environment variable `NODE_CHANNEL_FD` on the child process.
394
395Unlike the fork(2) POSIX system call, `child_process.fork()` does not clone the
396current process.
397
398The `shell` option available in [`child_process.spawn()`][] is not supported by
399`child_process.fork()` and will be ignored if set.
400
401### `child_process.spawn(command[, args][, options])`
402<!-- YAML
403added: v0.1.90
404changes:
405  - version: v12.16.0
406    pr-url: https://github.com/nodejs/node/pull/30162
407    description: The `serialization` option is supported now.
408  - version: v8.8.0
409    pr-url: https://github.com/nodejs/node/pull/15380
410    description: The `windowsHide` option is supported now.
411  - version: v6.4.0
412    pr-url: https://github.com/nodejs/node/pull/7696
413    description: The `argv0` option is supported now.
414  - version: v5.7.0
415    pr-url: https://github.com/nodejs/node/pull/4598
416    description: The `shell` option is supported now.
417-->
418
419* `command` {string} The command to run.
420* `args` {string[]} List of string arguments.
421* `options` {Object}
422  * `cwd` {string} Current working directory of the child process.
423  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
424  * `argv0` {string} Explicitly set the value of `argv[0]` sent to the child
425    process. This will be set to `command` if not specified.
426  * `stdio` {Array|string} Child's stdio configuration (see
427    [`options.stdio`][`stdio`]).
428  * `detached` {boolean} Prepare child to run independently of its parent
429    process. Specific behavior depends on the platform, see
430    [`options.detached`][]).
431  * `uid` {number} Sets the user identity of the process (see setuid(2)).
432  * `gid` {number} Sets the group identity of the process (see setgid(2)).
433  * `serialization` {string} Specify the kind of serialization used for sending
434    messages between processes. Possible values are `'json'` and `'advanced'`.
435    See [Advanced serialization][] for more details. **Default:** `'json'`.
436  * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
437    `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
438    shell can be specified as a string. See [Shell requirements][] and
439    [Default Windows shell][]. **Default:** `false` (no shell).
440  * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
441    done on Windows. Ignored on Unix. This is set to `true` automatically
442    when `shell` is specified and is CMD. **Default:** `false`.
443  * `windowsHide` {boolean} Hide the subprocess console window that would
444    normally be created on Windows systems. **Default:** `false`.
445* Returns: {ChildProcess}
446
447The `child_process.spawn()` method spawns a new process using the given
448`command`, with command line arguments in `args`. If omitted, `args` defaults
449to an empty array.
450
451**If the `shell` option is enabled, do not pass unsanitized user input to this
452function. Any input containing shell metacharacters may be used to trigger
453arbitrary command execution.**
454
455A third argument may be used to specify additional options, with these defaults:
456
457```js
458const defaults = {
459  cwd: undefined,
460  env: process.env
461};
462```
463
464Use `cwd` to specify the working directory from which the process is spawned.
465If not given, the default is to inherit the current working directory.
466
467Use `env` to specify environment variables that will be visible to the new
468process, the default is [`process.env`][].
469
470`undefined` values in `env` will be ignored.
471
472Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
473exit code:
474
475```js
476const { spawn } = require('child_process');
477const ls = spawn('ls', ['-lh', '/usr']);
478
479ls.stdout.on('data', (data) => {
480  console.log(`stdout: ${data}`);
481});
482
483ls.stderr.on('data', (data) => {
484  console.error(`stderr: ${data}`);
485});
486
487ls.on('close', (code) => {
488  console.log(`child process exited with code ${code}`);
489});
490```
491
492Example: A very elaborate way to run `ps ax | grep ssh`
493
494```js
495const { spawn } = require('child_process');
496const ps = spawn('ps', ['ax']);
497const grep = spawn('grep', ['ssh']);
498
499ps.stdout.on('data', (data) => {
500  grep.stdin.write(data);
501});
502
503ps.stderr.on('data', (data) => {
504  console.error(`ps stderr: ${data}`);
505});
506
507ps.on('close', (code) => {
508  if (code !== 0) {
509    console.log(`ps process exited with code ${code}`);
510  }
511  grep.stdin.end();
512});
513
514grep.stdout.on('data', (data) => {
515  console.log(data.toString());
516});
517
518grep.stderr.on('data', (data) => {
519  console.error(`grep stderr: ${data}`);
520});
521
522grep.on('close', (code) => {
523  if (code !== 0) {
524    console.log(`grep process exited with code ${code}`);
525  }
526});
527```
528
529Example of checking for failed `spawn`:
530
531```js
532const { spawn } = require('child_process');
533const subprocess = spawn('bad_command');
534
535subprocess.on('error', (err) => {
536  console.error('Failed to start subprocess.');
537});
538```
539
540Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process
541title while others (Windows, SunOS) will use `command`.
542
543Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so
544`process.argv[0]` in a Node.js child process will not match the `argv0`
545parameter passed to `spawn` from the parent, retrieve it with the
546`process.argv0` property instead.
547
548#### `options.detached`
549<!-- YAML
550added: v0.7.10
551-->
552
553On Windows, setting `options.detached` to `true` makes it possible for the
554child process to continue running after the parent exits. The child will have
555its own console window. Once enabled for a child process, it cannot be
556disabled.
557
558On non-Windows platforms, if `options.detached` is set to `true`, the child
559process will be made the leader of a new process group and session. Child
560processes may continue running after the parent exits regardless of whether
561they are detached or not. See setsid(2) for more information.
562
563By default, the parent will wait for the detached child to exit. To prevent the
564parent from waiting for a given `subprocess` to exit, use the
565`subprocess.unref()` method. Doing so will cause the parent's event loop to not
566include the child in its reference count, allowing the parent to exit
567independently of the child, unless there is an established IPC channel between
568the child and the parent.
569
570When using the `detached` option to start a long-running process, the process
571will not stay running in the background after the parent exits unless it is
572provided with a `stdio` configuration that is not connected to the parent.
573If the parent's `stdio` is inherited, the child will remain attached to the
574controlling terminal.
575
576Example of a long-running process, by detaching and also ignoring its parent
577`stdio` file descriptors, in order to ignore the parent's termination:
578
579```js
580const { spawn } = require('child_process');
581
582const subprocess = spawn(process.argv[0], ['child_program.js'], {
583  detached: true,
584  stdio: 'ignore'
585});
586
587subprocess.unref();
588```
589
590Alternatively one can redirect the child process' output into files:
591
592```js
593const fs = require('fs');
594const { spawn } = require('child_process');
595const out = fs.openSync('./out.log', 'a');
596const err = fs.openSync('./out.log', 'a');
597
598const subprocess = spawn('prg', [], {
599  detached: true,
600  stdio: [ 'ignore', out, err ]
601});
602
603subprocess.unref();
604```
605
606#### `options.stdio`
607<!-- YAML
608added: v0.7.10
609changes:
610  - version: v3.3.1
611    pr-url: https://github.com/nodejs/node/pull/2727
612    description: The value `0` is now accepted as a file descriptor.
613-->
614
615The `options.stdio` option is used to configure the pipes that are established
616between the parent and child process. By default, the child's stdin, stdout,
617and stderr are redirected to corresponding [`subprocess.stdin`][],
618[`subprocess.stdout`][], and [`subprocess.stderr`][] streams on the
619[`ChildProcess`][] object. This is equivalent to setting the `options.stdio`
620equal to `['pipe', 'pipe', 'pipe']`.
621
622For convenience, `options.stdio` may be one of the following strings:
623
624* `'pipe'`: equivalent to `['pipe', 'pipe', 'pipe']` (the default)
625* `'ignore'`: equivalent to `['ignore', 'ignore', 'ignore']`
626* `'inherit'`: equivalent to `['inherit', 'inherit', 'inherit']` or `[0, 1, 2]`
627
628Otherwise, the value of `options.stdio` is an array where each index corresponds
629to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
630and stderr, respectively. Additional fds can be specified to create additional
631pipes between the parent and child. The value is one of the following:
632
6331. `'pipe'`: Create a pipe between the child process and the parent process.
634   The parent end of the pipe is exposed to the parent as a property on the
635   `child_process` object as [`subprocess.stdio[fd]`][`subprocess.stdio`]. Pipes
636   created for fds 0, 1, and 2 are also available as [`subprocess.stdin`][],
637   [`subprocess.stdout`][] and [`subprocess.stderr`][], respectively.
6382. `'ipc'`: Create an IPC channel for passing messages/file descriptors
639   between parent and child. A [`ChildProcess`][] may have at most one IPC
640   stdio file descriptor. Setting this option enables the
641   [`subprocess.send()`][] method. If the child is a Node.js process, the
642   presence of an IPC channel will enable [`process.send()`][] and
643   [`process.disconnect()`][] methods, as well as [`'disconnect'`][] and
644   [`'message'`][] events within the child.
645
646   Accessing the IPC channel fd in any way other than [`process.send()`][]
647   or using the IPC channel with a child process that is not a Node.js instance
648   is not supported.
6493. `'ignore'`: Instructs Node.js to ignore the fd in the child. While Node.js
650   will always open fds 0, 1, and 2 for the processes it spawns, setting the fd
651   to `'ignore'` will cause Node.js to open `/dev/null` and attach it to the
652   child's fd.
6534. `'inherit'`: Pass through the corresponding stdio stream to/from the
654   parent process. In the first three positions, this is equivalent to
655   `process.stdin`, `process.stdout`, and `process.stderr`, respectively. In
656   any other position, equivalent to `'ignore'`.
6575. {Stream} object: Share a readable or writable stream that refers to a tty,
658   file, socket, or a pipe with the child process. The stream's underlying
659   file descriptor is duplicated in the child process to the fd that
660   corresponds to the index in the `stdio` array. The stream must have an
661   underlying descriptor (file streams do not until the `'open'` event has
662   occurred).
6636. Positive integer: The integer value is interpreted as a file descriptor
664   that is currently open in the parent process. It is shared with the child
665   process, similar to how {Stream} objects can be shared. Passing sockets
666   is not supported on Windows.
6677. `null`, `undefined`: Use default value. For stdio fds 0, 1, and 2 (in other
668   words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
669   default is `'ignore'`.
670
671```js
672const { spawn } = require('child_process');
673
674// Child will use parent's stdios.
675spawn('prg', [], { stdio: 'inherit' });
676
677// Spawn child sharing only stderr.
678spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
679
680// Open an extra fd=4, to interact with programs presenting a
681// startd-style interface.
682spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
683```
684
685*It is worth noting that when an IPC channel is established between the
686parent and child processes, and the child is a Node.js process, the child
687is launched with the IPC channel unreferenced (using `unref()`) until the
688child registers an event handler for the [`'disconnect'`][] event
689or the [`'message'`][] event. This allows the child to exit
690normally without the process being held open by the open IPC channel.*
691
692On Unix-like operating systems, the [`child_process.spawn()`][] method
693performs memory operations synchronously before decoupling the event loop
694from the child. Applications with a large memory footprint may find frequent
695[`child_process.spawn()`][] calls to be a bottleneck. For more information,
696see [V8 issue 7381](https://bugs.chromium.org/p/v8/issues/detail?id=7381).
697
698See also: [`child_process.exec()`][] and [`child_process.fork()`][].
699
700## Synchronous process creation
701
702The [`child_process.spawnSync()`][], [`child_process.execSync()`][], and
703[`child_process.execFileSync()`][] methods are synchronous and will block the
704Node.js event loop, pausing execution of any additional code until the spawned
705process exits.
706
707Blocking calls like these are mostly useful for simplifying general-purpose
708scripting tasks and for simplifying the loading/processing of application
709configuration at startup.
710
711### `child_process.execFileSync(file[, args][, options])`
712<!-- YAML
713added: v0.11.12
714changes:
715  - version: v10.10.0
716    pr-url: https://github.com/nodejs/node/pull/22409
717    description: The `input` option can now be any `TypedArray` or a
718                 `DataView`.
719  - version: v8.8.0
720    pr-url: https://github.com/nodejs/node/pull/15380
721    description: The `windowsHide` option is supported now.
722  - version: v8.0.0
723    pr-url: https://github.com/nodejs/node/pull/10653
724    description: The `input` option can now be a `Uint8Array`.
725  - version: v6.2.1, v4.5.0
726    pr-url: https://github.com/nodejs/node/pull/6939
727    description: The `encoding` option can now explicitly be set to `buffer`.
728-->
729
730* `file` {string} The name or path of the executable file to run.
731* `args` {string[]} List of string arguments.
732* `options` {Object}
733  * `cwd` {string} Current working directory of the child process.
734  * `input` {string|Buffer|TypedArray|DataView} The value which will be passed
735    as stdin to the spawned process. Supplying this value will override
736    `stdio[0]`.
737  * `stdio` {string|Array} Child's stdio configuration. `stderr` by default will
738    be output to the parent process' stderr unless `stdio` is specified.
739    **Default:** `'pipe'`.
740  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
741  * `uid` {number} Sets the user identity of the process (see setuid(2)).
742  * `gid` {number} Sets the group identity of the process (see setgid(2)).
743  * `timeout` {number} In milliseconds the maximum amount of time the process
744    is allowed to run. **Default:** `undefined`.
745  * `killSignal` {string|integer} The signal value to be used when the spawned
746    process will be killed. **Default:** `'SIGTERM'`.
747  * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
748    stderr. If exceeded, the child process is terminated. See caveat at
749    [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.
750  * `encoding` {string} The encoding used for all stdio inputs and outputs.
751    **Default:** `'buffer'`.
752  * `windowsHide` {boolean} Hide the subprocess console window that would
753    normally be created on Windows systems. **Default:** `false`.
754  * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
755    `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
756    shell can be specified as a string. See [Shell requirements][] and
757    [Default Windows shell][]. **Default:** `false` (no shell).
758* Returns: {Buffer|string} The stdout from the command.
759
760The `child_process.execFileSync()` method is generally identical to
761[`child_process.execFile()`][] with the exception that the method will not
762return until the child process has fully closed. When a timeout has been
763encountered and `killSignal` is sent, the method won't return until the process
764has completely exited.
765
766If the child process intercepts and handles the `SIGTERM` signal and
767does not exit, the parent process will still wait until the child process has
768exited.
769
770If the process times out or has a non-zero exit code, this method will throw an
771[`Error`][] that will include the full result of the underlying
772[`child_process.spawnSync()`][].
773
774**If the `shell` option is enabled, do not pass unsanitized user input to this
775function. Any input containing shell metacharacters may be used to trigger
776arbitrary command execution.**
777
778### `child_process.execSync(command[, options])`
779<!-- YAML
780added: v0.11.12
781changes:
782  - version: v10.10.0
783    pr-url: https://github.com/nodejs/node/pull/22409
784    description: The `input` option can now be any `TypedArray` or a
785                 `DataView`.
786  - version: v8.8.0
787    pr-url: https://github.com/nodejs/node/pull/15380
788    description: The `windowsHide` option is supported now.
789  - version: v8.0.0
790    pr-url: https://github.com/nodejs/node/pull/10653
791    description: The `input` option can now be a `Uint8Array`.
792-->
793
794* `command` {string} The command to run.
795* `options` {Object}
796  * `cwd` {string} Current working directory of the child process.
797  * `input` {string|Buffer|TypedArray|DataView} The value which will be passed
798    as stdin to the spawned process. Supplying this value will override
799    `stdio[0]`.
800  * `stdio` {string|Array} Child's stdio configuration. `stderr` by default will
801    be output to the parent process' stderr unless `stdio` is specified.
802    **Default:** `'pipe'`.
803  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
804  * `shell` {string} Shell to execute the command with. See
805    [Shell requirements][] and [Default Windows shell][]. **Default:**
806    `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.
807  * `uid` {number} Sets the user identity of the process. (See setuid(2)).
808  * `gid` {number} Sets the group identity of the process. (See setgid(2)).
809  * `timeout` {number} In milliseconds the maximum amount of time the process
810    is allowed to run. **Default:** `undefined`.
811  * `killSignal` {string|integer} The signal value to be used when the spawned
812    process will be killed. **Default:** `'SIGTERM'`.
813  * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
814    stderr. If exceeded, the child process is terminated and any output is
815    truncated. See caveat at [`maxBuffer` and Unicode][].
816    **Default:** `1024 * 1024`.
817  * `encoding` {string} The encoding used for all stdio inputs and outputs.
818    **Default:** `'buffer'`.
819  * `windowsHide` {boolean} Hide the subprocess console window that would
820    normally be created on Windows systems. **Default:** `false`.
821* Returns: {Buffer|string} The stdout from the command.
822
823The `child_process.execSync()` method is generally identical to
824[`child_process.exec()`][] with the exception that the method will not return
825until the child process has fully closed. When a timeout has been encountered
826and `killSignal` is sent, the method won't return until the process has
827completely exited. If the child process intercepts and handles the `SIGTERM`
828signal and doesn't exit, the parent process will wait until the child process
829has exited.
830
831If the process times out or has a non-zero exit code, this method will throw.
832The [`Error`][] object will contain the entire result from
833[`child_process.spawnSync()`][].
834
835**Never pass unsanitized user input to this function. Any input containing shell
836metacharacters may be used to trigger arbitrary command execution.**
837
838### `child_process.spawnSync(command[, args][, options])`
839<!-- YAML
840added: v0.11.12
841changes:
842  - version: v10.10.0
843    pr-url: https://github.com/nodejs/node/pull/22409
844    description: The `input` option can now be any `TypedArray` or a
845                 `DataView`.
846  - version: v8.8.0
847    pr-url: https://github.com/nodejs/node/pull/15380
848    description: The `windowsHide` option is supported now.
849  - version: v8.0.0
850    pr-url: https://github.com/nodejs/node/pull/10653
851    description: The `input` option can now be a `Uint8Array`.
852  - version: v6.2.1, v4.5.0
853    pr-url: https://github.com/nodejs/node/pull/6939
854    description: The `encoding` option can now explicitly be set to `buffer`.
855  - version: v5.7.0
856    pr-url: https://github.com/nodejs/node/pull/4598
857    description: The `shell` option is supported now.
858-->
859
860* `command` {string} The command to run.
861* `args` {string[]} List of string arguments.
862* `options` {Object}
863  * `cwd` {string} Current working directory of the child process.
864  * `input` {string|Buffer|TypedArray|DataView} The value which will be passed
865    as stdin to the spawned process. Supplying this value will override
866    `stdio[0]`.
867  * `argv0` {string} Explicitly set the value of `argv[0]` sent to the child
868    process. This will be set to `command` if not specified.
869  * `stdio` {string|Array} Child's stdio configuration.
870  * `env` {Object} Environment key-value pairs. **Default:** `process.env`.
871  * `uid` {number} Sets the user identity of the process (see setuid(2)).
872  * `gid` {number} Sets the group identity of the process (see setgid(2)).
873  * `timeout` {number} In milliseconds the maximum amount of time the process
874    is allowed to run. **Default:** `undefined`.
875  * `killSignal` {string|integer} The signal value to be used when the spawned
876    process will be killed. **Default:** `'SIGTERM'`.
877  * `maxBuffer` {number} Largest amount of data in bytes allowed on stdout or
878    stderr. If exceeded, the child process is terminated and any output is
879    truncated. See caveat at [`maxBuffer` and Unicode][].
880    **Default:** `1024 * 1024`.
881  * `encoding` {string} The encoding used for all stdio inputs and outputs.
882    **Default:** `'buffer'`.
883  * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
884    `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
885    shell can be specified as a string. See [Shell requirements][] and
886    [Default Windows shell][]. **Default:** `false` (no shell).
887  * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
888    done on Windows. Ignored on Unix. This is set to `true` automatically
889    when `shell` is specified and is CMD. **Default:** `false`.
890  * `windowsHide` {boolean} Hide the subprocess console window that would
891    normally be created on Windows systems. **Default:** `false`.
892* Returns: {Object}
893  * `pid` {number} Pid of the child process.
894  * `output` {Array} Array of results from stdio output.
895  * `stdout` {Buffer|string} The contents of `output[1]`.
896  * `stderr` {Buffer|string} The contents of `output[2]`.
897  * `status` {number|null} The exit code of the subprocess, or `null` if the
898    subprocess terminated due to a signal.
899  * `signal` {string|null} The signal used to kill the subprocess, or `null` if
900    the subprocess did not terminate due to a signal.
901  * `error` {Error} The error object if the child process failed or timed out.
902
903The `child_process.spawnSync()` method is generally identical to
904[`child_process.spawn()`][] with the exception that the function will not return
905until the child process has fully closed. When a timeout has been encountered
906and `killSignal` is sent, the method won't return until the process has
907completely exited. If the process intercepts and handles the `SIGTERM` signal
908and doesn't exit, the parent process will wait until the child process has
909exited.
910
911**If the `shell` option is enabled, do not pass unsanitized user input to this
912function. Any input containing shell metacharacters may be used to trigger
913arbitrary command execution.**
914
915## Class: `ChildProcess`
916<!-- YAML
917added: v2.2.0
918-->
919
920* Extends: {EventEmitter}
921
922Instances of the `ChildProcess` represent spawned child processes.
923
924Instances of `ChildProcess` are not intended to be created directly. Rather,
925use the [`child_process.spawn()`][], [`child_process.exec()`][],
926[`child_process.execFile()`][], or [`child_process.fork()`][] methods to create
927instances of `ChildProcess`.
928
929### Event: `'close'`
930<!-- YAML
931added: v0.7.7
932-->
933
934* `code` {number} The exit code if the child exited on its own.
935* `signal` {string} The signal by which the child process was terminated.
936
937The `'close'` event is emitted when the stdio streams of a child process have
938been closed. This is distinct from the [`'exit'`][] event, since multiple
939processes might share the same stdio streams.
940
941```js
942const { spawn } = require('child_process');
943const ls = spawn('ls', ['-lh', '/usr']);
944
945ls.stdout.on('data', (data) => {
946  console.log(`stdout: ${data}`);
947});
948
949ls.on('close', (code) => {
950  console.log(`child process close all stdio with code ${code}`);
951});
952
953ls.on('exit', (code) => {
954  console.log(`child process exited with code ${code}`);
955});
956```
957
958### Event: `'disconnect'`
959<!-- YAML
960added: v0.7.2
961-->
962
963The `'disconnect'` event is emitted after calling the
964[`subprocess.disconnect()`][] method in parent process or
965[`process.disconnect()`][] in child process. After disconnecting it is no longer
966possible to send or receive messages, and the [`subprocess.connected`][]
967property is `false`.
968
969### Event: `'error'`
970
971* `err` {Error} The error.
972
973The `'error'` event is emitted whenever:
974
9751. The process could not be spawned, or
9762. The process could not be killed, or
9773. Sending a message to the child process failed.
978
979The `'exit'` event may or may not fire after an error has occurred. When
980listening to both the `'exit'` and `'error'` events, guard
981against accidentally invoking handler functions multiple times.
982
983See also [`subprocess.kill()`][] and [`subprocess.send()`][].
984
985### Event: `'exit'`
986<!-- YAML
987added: v0.1.90
988-->
989
990* `code` {number} The exit code if the child exited on its own.
991* `signal` {string} The signal by which the child process was terminated.
992
993The `'exit'` event is emitted after the child process ends. If the process
994exited, `code` is the final exit code of the process, otherwise `null`. If the
995process terminated due to receipt of a signal, `signal` is the string name of
996the signal, otherwise `null`. One of the two will always be non-`null`.
997
998When the `'exit'` event is triggered, child process stdio streams might still be
999open.
1000
1001Node.js establishes signal handlers for `SIGINT` and `SIGTERM` and Node.js
1002processes will not terminate immediately due to receipt of those signals.
1003Rather, Node.js will perform a sequence of cleanup actions and then will
1004re-raise the handled signal.
1005
1006See waitpid(2).
1007
1008### Event: `'message'`
1009<!-- YAML
1010added: v0.5.9
1011-->
1012
1013* `message` {Object} A parsed JSON object or primitive value.
1014* `sendHandle` {Handle} A [`net.Socket`][] or [`net.Server`][] object, or
1015  undefined.
1016
1017The `'message'` event is triggered when a child process uses
1018[`process.send()`][] to send messages.
1019
1020The message goes through serialization and parsing. The resulting
1021message might not be the same as what is originally sent.
1022
1023If the `serialization` option was set to `'advanced'` used when spawning the
1024child process, the `message` argument can contain data that JSON is not able
1025to represent.
1026See [Advanced serialization][] for more details.
1027
1028### `subprocess.channel`
1029<!-- YAML
1030added: v7.1.0
1031-->
1032
1033* {Object} A pipe representing the IPC channel to the child process.
1034
1035The `subprocess.channel` property is a reference to the child's IPC channel. If
1036no IPC channel currently exists, this property is `undefined`.
1037
1038### `subprocess.connected`
1039<!-- YAML
1040added: v0.7.2
1041-->
1042
1043* {boolean} Set to `false` after `subprocess.disconnect()` is called.
1044
1045The `subprocess.connected` property indicates whether it is still possible to
1046send and receive messages from a child process. When `subprocess.connected` is
1047`false`, it is no longer possible to send or receive messages.
1048
1049### `subprocess.disconnect()`
1050<!-- YAML
1051added: v0.7.2
1052-->
1053
1054Closes the IPC channel between parent and child, allowing the child to exit
1055gracefully once there are no other connections keeping it alive. After calling
1056this method the `subprocess.connected` and `process.connected` properties in
1057both the parent and child (respectively) will be set to `false`, and it will be
1058no longer possible to pass messages between the processes.
1059
1060The `'disconnect'` event will be emitted when there are no messages in the
1061process of being received. This will most often be triggered immediately after
1062calling `subprocess.disconnect()`.
1063
1064When the child process is a Node.js instance (e.g. spawned using
1065[`child_process.fork()`][]), the `process.disconnect()` method can be invoked
1066within the child process to close the IPC channel as well.
1067
1068### `subprocess.exitCode`
1069
1070* {integer}
1071
1072The `subprocess.exitCode` property indicates the exit code of the child process.
1073If the child process is still running, the field will be `null`.
1074
1075### `subprocess.kill([signal])`
1076<!-- YAML
1077added: v0.1.90
1078-->
1079
1080* `signal` {number|string}
1081* Returns: {boolean}
1082
1083The `subprocess.kill()` method sends a signal to the child process. If no
1084argument is given, the process will be sent the `'SIGTERM'` signal. See
1085signal(7) for a list of available signals. This function returns `true` if
1086kill(2) succeeds, and `false` otherwise.
1087
1088```js
1089const { spawn } = require('child_process');
1090const grep = spawn('grep', ['ssh']);
1091
1092grep.on('close', (code, signal) => {
1093  console.log(
1094    `child process terminated due to receipt of signal ${signal}`);
1095});
1096
1097// Send SIGHUP to process.
1098grep.kill('SIGHUP');
1099```
1100
1101The [`ChildProcess`][] object may emit an [`'error'`][] event if the signal
1102cannot be delivered. Sending a signal to a child process that has already exited
1103is not an error but may have unforeseen consequences. Specifically, if the
1104process identifier (PID) has been reassigned to another process, the signal will
1105be delivered to that process instead which can have unexpected results.
1106
1107While the function is called `kill`, the signal delivered to the child process
1108may not actually terminate the process.
1109
1110See kill(2) for reference.
1111
1112On Linux, child processes of child processes will not be terminated
1113when attempting to kill their parent. This is likely to happen when running a
1114new process in a shell or with the use of the `shell` option of `ChildProcess`:
1115
1116```js
1117'use strict';
1118const { spawn } = require('child_process');
1119
1120const subprocess = spawn(
1121  'sh',
1122  [
1123    '-c',
1124    `node -e "setInterval(() => {
1125      console.log(process.pid, 'is alive')
1126    }, 500);"`
1127  ], {
1128    stdio: ['inherit', 'inherit', 'inherit']
1129  }
1130);
1131
1132setTimeout(() => {
1133  subprocess.kill(); // Does not terminate the Node.js process in the shell.
1134}, 2000);
1135```
1136
1137### `subprocess.killed`
1138<!-- YAML
1139added: v0.5.10
1140-->
1141
1142* {boolean} Set to `true` after `subprocess.kill()` is used to successfully
1143  send a signal to the child process.
1144
1145The `subprocess.killed` property indicates whether the child process
1146successfully received a signal from `subprocess.kill()`. The `killed` property
1147does not indicate that the child process has been terminated.
1148
1149### `subprocess.pid`
1150<!-- YAML
1151added: v0.1.90
1152-->
1153
1154* {integer}
1155
1156Returns the process identifier (PID) of the child process.
1157
1158```js
1159const { spawn } = require('child_process');
1160const grep = spawn('grep', ['ssh']);
1161
1162console.log(`Spawned child pid: ${grep.pid}`);
1163grep.stdin.end();
1164```
1165
1166### `subprocess.ref()`
1167<!-- YAML
1168added: v0.7.10
1169-->
1170
1171Calling `subprocess.ref()` after making a call to `subprocess.unref()` will
1172restore the removed reference count for the child process, forcing the parent
1173to wait for the child to exit before exiting itself.
1174
1175```js
1176const { spawn } = require('child_process');
1177
1178const subprocess = spawn(process.argv[0], ['child_program.js'], {
1179  detached: true,
1180  stdio: 'ignore'
1181});
1182
1183subprocess.unref();
1184subprocess.ref();
1185```
1186
1187### `subprocess.send(message[, sendHandle[, options]][, callback])`
1188<!-- YAML
1189added: v0.5.9
1190changes:
1191  - version: v5.8.0
1192    pr-url: https://github.com/nodejs/node/pull/5283
1193    description: The `options` parameter, and the `keepOpen` option
1194                 in particular, is supported now.
1195  - version: v5.0.0
1196    pr-url: https://github.com/nodejs/node/pull/3516
1197    description: This method returns a boolean for flow control now.
1198  - version: v4.0.0
1199    pr-url: https://github.com/nodejs/node/pull/2620
1200    description: The `callback` parameter is supported now.
1201-->
1202
1203* `message` {Object}
1204* `sendHandle` {Handle}
1205* `options` {Object} The `options` argument, if present, is an object used to
1206  parameterize the sending of certain types of handles. `options` supports
1207  the following properties:
1208  * `keepOpen` {boolean} A value that can be used when passing instances of
1209    `net.Socket`. When `true`, the socket is kept open in the sending process.
1210    **Default:** `false`.
1211* `callback` {Function}
1212* Returns: {boolean}
1213
1214When an IPC channel has been established between the parent and child (
1215i.e. when using [`child_process.fork()`][]), the `subprocess.send()` method can
1216be used to send messages to the child process. When the child process is a
1217Node.js instance, these messages can be received via the [`'message'`][] event.
1218
1219The message goes through serialization and parsing. The resulting
1220message might not be the same as what is originally sent.
1221
1222For example, in the parent script:
1223
1224```js
1225const cp = require('child_process');
1226const n = cp.fork(`${__dirname}/sub.js`);
1227
1228n.on('message', (m) => {
1229  console.log('PARENT got message:', m);
1230});
1231
1232// Causes the child to print: CHILD got message: { hello: 'world' }
1233n.send({ hello: 'world' });
1234```
1235
1236And then the child script, `'sub.js'` might look like this:
1237
1238```js
1239process.on('message', (m) => {
1240  console.log('CHILD got message:', m);
1241});
1242
1243// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
1244process.send({ foo: 'bar', baz: NaN });
1245```
1246
1247Child Node.js processes will have a [`process.send()`][] method of their own
1248that allows the child to send messages back to the parent.
1249
1250There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages
1251containing a `NODE_` prefix in the `cmd` property are reserved for use within
1252Node.js core and will not be emitted in the child's [`'message'`][]
1253event. Rather, such messages are emitted using the
1254`'internalMessage'` event and are consumed internally by Node.js.
1255Applications should avoid using such messages or listening for
1256`'internalMessage'` events as it is subject to change without notice.
1257
1258The optional `sendHandle` argument that may be passed to `subprocess.send()` is
1259for passing a TCP server or socket object to the child process. The child will
1260receive the object as the second argument passed to the callback function
1261registered on the [`'message'`][] event. Any data that is received
1262and buffered in the socket will not be sent to the child.
1263
1264The optional `callback` is a function that is invoked after the message is
1265sent but before the child may have received it. The function is called with a
1266single argument: `null` on success, or an [`Error`][] object on failure.
1267
1268If no `callback` function is provided and the message cannot be sent, an
1269`'error'` event will be emitted by the [`ChildProcess`][] object. This can
1270happen, for instance, when the child process has already exited.
1271
1272`subprocess.send()` will return `false` if the channel has closed or when the
1273backlog of unsent messages exceeds a threshold that makes it unwise to send
1274more. Otherwise, the method returns `true`. The `callback` function can be
1275used to implement flow control.
1276
1277#### Example: sending a server object
1278
1279The `sendHandle` argument can be used, for instance, to pass the handle of
1280a TCP server object to the child process as illustrated in the example below:
1281
1282```js
1283const subprocess = require('child_process').fork('subprocess.js');
1284
1285// Open up the server object and send the handle.
1286const server = require('net').createServer();
1287server.on('connection', (socket) => {
1288  socket.end('handled by parent');
1289});
1290server.listen(1337, () => {
1291  subprocess.send('server', server);
1292});
1293```
1294
1295The child would then receive the server object as:
1296
1297```js
1298process.on('message', (m, server) => {
1299  if (m === 'server') {
1300    server.on('connection', (socket) => {
1301      socket.end('handled by child');
1302    });
1303  }
1304});
1305```
1306
1307Once the server is now shared between the parent and child, some connections
1308can be handled by the parent and some by the child.
1309
1310While the example above uses a server created using the `net` module, `dgram`
1311module servers use exactly the same workflow with the exceptions of listening on
1312a `'message'` event instead of `'connection'` and using `server.bind()` instead
1313of `server.listen()`. This is, however, currently only supported on Unix
1314platforms.
1315
1316#### Example: sending a socket object
1317
1318Similarly, the `sendHandler` argument can be used to pass the handle of a
1319socket to the child process. The example below spawns two children that each
1320handle connections with "normal" or "special" priority:
1321
1322```js
1323const { fork } = require('child_process');
1324const normal = fork('subprocess.js', ['normal']);
1325const special = fork('subprocess.js', ['special']);
1326
1327// Open up the server and send sockets to child. Use pauseOnConnect to prevent
1328// the sockets from being read before they are sent to the child process.
1329const server = require('net').createServer({ pauseOnConnect: true });
1330server.on('connection', (socket) => {
1331
1332  // If this is special priority...
1333  if (socket.remoteAddress === '74.125.127.100') {
1334    special.send('socket', socket);
1335    return;
1336  }
1337  // This is normal priority.
1338  normal.send('socket', socket);
1339});
1340server.listen(1337);
1341```
1342
1343The `subprocess.js` would receive the socket handle as the second argument
1344passed to the event callback function:
1345
1346```js
1347process.on('message', (m, socket) => {
1348  if (m === 'socket') {
1349    if (socket) {
1350      // Check that the client socket exists.
1351      // It is possible for the socket to be closed between the time it is
1352      // sent and the time it is received in the child process.
1353      socket.end(`Request handled with ${process.argv[2]} priority`);
1354    }
1355  }
1356});
1357```
1358
1359Do not use `.maxConnections` on a socket that has been passed to a subprocess.
1360The parent cannot track when the socket is destroyed.
1361
1362Any `'message'` handlers in the subprocess should verify that `socket` exists,
1363as the connection may have been closed during the time it takes to send the
1364connection to the child.
1365
1366### `subprocess.signalCode`
1367
1368* {integer}
1369
1370The `subprocess.signalCode` property indicates the signal number received by
1371the child process if any, else `null`.
1372
1373### `subprocess.spawnargs`
1374
1375* {Array}
1376
1377The `subprocess.spawnargs` property represents the full list of command line
1378arguments the child process was launched with.
1379
1380### `subprocess.spawnfile`
1381
1382* {string}
1383
1384The `subprocess.spawnfile` property indicates the executable file name of
1385the child process that is launched.
1386
1387For [`child_process.fork()`][], its value will be equal to
1388[`process.execPath`][].
1389For [`child_process.spawn()`][], its value will be the name of
1390the executable file.
1391For [`child_process.exec()`][],  its value will be the name of the shell
1392in which the child process is launched.
1393
1394### `subprocess.stderr`
1395<!-- YAML
1396added: v0.1.90
1397-->
1398
1399* {stream.Readable}
1400
1401A `Readable Stream` that represents the child process's `stderr`.
1402
1403If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
1404then this will be `null`.
1405
1406`subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will
1407refer to the same value.
1408
1409### `subprocess.stdin`
1410<!-- YAML
1411added: v0.1.90
1412-->
1413
1414* {stream.Writable}
1415
1416A `Writable Stream` that represents the child process's `stdin`.
1417
1418If a child process waits to read all of its input, the child will not continue
1419until this stream has been closed via `end()`.
1420
1421If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
1422then this will be `null`.
1423
1424`subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will
1425refer to the same value.
1426
1427### `subprocess.stdio`
1428<!-- YAML
1429added: v0.7.10
1430-->
1431
1432* {Array}
1433
1434A sparse array of pipes to the child process, corresponding with positions in
1435the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
1436to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and
1437`subprocess.stdio[2]` are also available as `subprocess.stdin`,
1438`subprocess.stdout`, and `subprocess.stderr`, respectively.
1439
1440In the following example, only the child's fd `1` (stdout) is configured as a
1441pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values
1442in the array are `null`.
1443
1444```js
1445const assert = require('assert');
1446const fs = require('fs');
1447const child_process = require('child_process');
1448
1449const subprocess = child_process.spawn('ls', {
1450  stdio: [
1451    0, // Use parent's stdin for child.
1452    'pipe', // Pipe child's stdout to parent.
1453    fs.openSync('err.out', 'w') // Direct child's stderr to a file.
1454  ]
1455});
1456
1457assert.strictEqual(subprocess.stdio[0], null);
1458assert.strictEqual(subprocess.stdio[0], subprocess.stdin);
1459
1460assert(subprocess.stdout);
1461assert.strictEqual(subprocess.stdio[1], subprocess.stdout);
1462
1463assert.strictEqual(subprocess.stdio[2], null);
1464assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
1465```
1466
1467### `subprocess.stdout`
1468<!-- YAML
1469added: v0.1.90
1470-->
1471
1472* {stream.Readable}
1473
1474A `Readable Stream` that represents the child process's `stdout`.
1475
1476If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
1477then this will be `null`.
1478
1479`subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will
1480refer to the same value.
1481
1482```js
1483const { spawn } = require('child_process');
1484
1485const subprocess = spawn('ls');
1486
1487subprocess.stdout.on('data', (data) => {
1488  console.log(`Received chunk ${data}`);
1489});
1490```
1491
1492### `subprocess.unref()`
1493<!-- YAML
1494added: v0.7.10
1495-->
1496
1497By default, the parent will wait for the detached child to exit. To prevent the
1498parent from waiting for a given `subprocess` to exit, use the
1499`subprocess.unref()` method. Doing so will cause the parent's event loop to not
1500include the child in its reference count, allowing the parent to exit
1501independently of the child, unless there is an established IPC channel between
1502the child and the parent.
1503
1504```js
1505const { spawn } = require('child_process');
1506
1507const subprocess = spawn(process.argv[0], ['child_program.js'], {
1508  detached: true,
1509  stdio: 'ignore'
1510});
1511
1512subprocess.unref();
1513```
1514
1515## `maxBuffer` and Unicode
1516
1517The `maxBuffer` option specifies the largest number of bytes allowed on `stdout`
1518or `stderr`. If this value is exceeded, then the child process is terminated.
1519This impacts output that includes multibyte character encodings such as UTF-8 or
1520UTF-16. For instance, `console.log('中文测试')` will send 13 UTF-8 encoded bytes
1521to `stdout` although there are only 4 characters.
1522
1523## Shell requirements
1524
1525The shell should understand the `-c` switch. If the shell is `'cmd.exe'`, it
1526should understand the `/d /s /c` switches and command line parsing should be
1527compatible.
1528
1529## Default Windows shell
1530
1531Although Microsoft specifies `%COMSPEC%` must contain the path to
1532`'cmd.exe'` in the root environment, child processes are not always subject to
1533the same requirement. Thus, in `child_process` functions where a shell can be
1534spawned, `'cmd.exe'` is used as a fallback if `process.env.ComSpec` is
1535unavailable.
1536
1537## Advanced serialization
1538<!-- YAML
1539added: v12.16.0
1540-->
1541
1542Child processes support a serialization mechanism for IPC that is based on the
1543[serialization API of the `v8` module][v8.serdes], based on the
1544[HTML structured clone algorithm][]. This is generally more powerful and
1545supports more built-in JavaScript object types, such as `BigInt`, `Map`
1546and `Set`, `ArrayBuffer` and `TypedArray`, `Buffer`, `Error`, `RegExp` etc.
1547
1548However, this format is not a full superset of JSON, and e.g. properties set on
1549objects of such built-in types will not be passed on through the serialization
1550step. Additionally, performance may not be equivalent to that of JSON, depending
1551on the structure of the passed data.
1552Therefore, this feature requires opting in by setting the
1553`serialization` option to `'advanced'` when calling [`child_process.spawn()`][]
1554or [`child_process.fork()`][].
1555
1556[Advanced serialization]: #child_process_advanced_serialization
1557[`'disconnect'`]: process.html#process_event_disconnect
1558[`'error'`]: #child_process_event_error
1559[`'exit'`]: #child_process_event_exit
1560[`'message'`]: process.html#process_event_message
1561[`ChildProcess`]: #child_process_child_process
1562[`Error`]: errors.html#errors_class_error
1563[`EventEmitter`]: events.html#events_class_eventemitter
1564[`child_process.exec()`]: #child_process_child_process_exec_command_options_callback
1565[`child_process.execFile()`]: #child_process_child_process_execfile_file_args_options_callback
1566[`child_process.execFileSync()`]: #child_process_child_process_execfilesync_file_args_options
1567[`child_process.execSync()`]: #child_process_child_process_execsync_command_options
1568[`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
1569[`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options
1570[`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options
1571[`maxBuffer` and Unicode]: #child_process_maxbuffer_and_unicode
1572[`net.Server`]: net.html#net_class_net_server
1573[`net.Socket`]: net.html#net_class_net_socket
1574[`options.detached`]: #child_process_options_detached
1575[`process.disconnect()`]: process.html#process_process_disconnect
1576[`process.env`]: process.html#process_process_env
1577[`process.execPath`]: process.html#process_process_execpath
1578[`process.send()`]: process.html#process_process_send_message_sendhandle_options_callback
1579[`stdio`]: #child_process_options_stdio
1580[`subprocess.connected`]: #child_process_subprocess_connected
1581[`subprocess.disconnect()`]: #child_process_subprocess_disconnect
1582[`subprocess.kill()`]: #child_process_subprocess_kill_signal
1583[`subprocess.send()`]: #child_process_subprocess_send_message_sendhandle_options_callback
1584[`subprocess.stderr`]: #child_process_subprocess_stderr
1585[`subprocess.stdin`]: #child_process_subprocess_stdin
1586[`subprocess.stdio`]: #child_process_subprocess_stdio
1587[`subprocess.stdout`]: #child_process_subprocess_stdout
1588[`util.promisify()`]: util.html#util_util_promisify_original
1589[Default Windows shell]: #child_process_default_windows_shell
1590[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
1591[Shell requirements]: #child_process_shell_requirements
1592[synchronous counterparts]: #child_process_synchronous_process_creation
1593[v8.serdes]: v8.html#v8_serialization_api
1594