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