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