{ "type": "module", "source": "doc/api/child_process.md", "modules": [ { "textRaw": "Child process", "name": "child_process", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/child_process.js
\nThe node:child_process
module provides the ability to spawn subprocesses in\na manner that is similar, but not identical, to popen(3)
. This capability\nis primarily provided by the child_process.spawn()
function:
const { spawn } = require('node:child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n
\nBy default, pipes for stdin
, stdout
, and stderr
are established between\nthe parent Node.js process and the spawned subprocess. These pipes have\nlimited (and platform-specific) capacity. If the subprocess writes to\nstdout in excess of that limit without the output being captured, the\nsubprocess blocks waiting for the pipe buffer to accept more data. This is\nidentical to the behavior of pipes in the shell. Use the { stdio: 'ignore' }
\noption if the output will not be consumed.
The command lookup is performed using the options.env.PATH
environment\nvariable if env
is in the options
object. Otherwise, process.env.PATH
is\nused. If options.env
is set without PATH
, lookup on Unix is performed\non a default search path search of /usr/bin:/bin
(see your operating system's\nmanual for execvpe/execvp), on Windows the current processes environment\nvariable PATH
is used.
On Windows, environment variables are case-insensitive. Node.js\nlexicographically sorts the env
keys and uses the first one that\ncase-insensitively matches. Only first (in lexicographic order) entry will be\npassed to the subprocess. This might lead to issues on Windows when passing\nobjects to the env
option that have multiple variants of the same key, such as\nPATH
and Path
.
The child_process.spawn()
method spawns the child process asynchronously,\nwithout blocking the Node.js event loop. The child_process.spawnSync()
\nfunction provides equivalent functionality in a synchronous manner that blocks\nthe event loop until the spawned process either exits or is terminated.
For convenience, the node:child_process
module provides a handful of\nsynchronous and asynchronous alternatives to child_process.spawn()
and\nchild_process.spawnSync()
. Each of these alternatives are implemented on\ntop of child_process.spawn()
or child_process.spawnSync()
.
child_process.exec()
: spawns a shell and runs a command within that\nshell, passing the stdout
and stderr
to a callback function when\ncomplete.child_process.execFile()
: similar to child_process.exec()
except\nthat it spawns the command directly without first spawning a shell by\ndefault.child_process.fork()
: spawns a new Node.js process and invokes a\nspecified module with an IPC communication channel established that allows\nsending messages between parent and child.child_process.execSync()
: a synchronous version of\nchild_process.exec()
that will block the Node.js event loop.child_process.execFileSync()
: a synchronous version of\nchild_process.execFile()
that will block the Node.js event loop.For certain use cases, such as automating shell scripts, the\nsynchronous counterparts may be more convenient. In many cases, however,\nthe synchronous methods can have significant impact on performance due to\nstalling the event loop while spawned processes complete.
", "modules": [ { "textRaw": "Asynchronous process creation", "name": "asynchronous_process_creation", "desc": "The child_process.spawn()
, child_process.fork()
, child_process.exec()
,\nand child_process.execFile()
methods all follow the idiomatic asynchronous\nprogramming pattern typical of other Node.js APIs.
Each of the methods returns a ChildProcess
instance. These objects\nimplement the Node.js EventEmitter
API, allowing the parent process to\nregister listener functions that are called when certain events occur during\nthe life cycle of the child process.
The child_process.exec()
and child_process.execFile()
methods\nadditionally allow for an optional callback
function to be specified that is\ninvoked when the child process terminates.
The importance of the distinction between child_process.exec()
and\nchild_process.execFile()
can vary based on platform. On Unix-type\noperating systems (Unix, Linux, macOS) child_process.execFile()
can be\nmore efficient because it does not spawn a shell by default. On Windows,\nhowever, .bat
and .cmd
files are not executable on their own without a\nterminal, and therefore cannot be launched using child_process.execFile()
.\nWhen running on Windows, .bat
and .cmd
files can be invoked using\nchild_process.spawn()
with the shell
option set, with\nchild_process.exec()
, or by spawning cmd.exe
and passing the .bat
or\n.cmd
file as an argument (which is what the shell
option and\nchild_process.exec()
do). In any case, if the script filename contains\nspaces it needs to be quoted.
// On Windows Only...\nconst { spawn } = require('node:child_process');\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\nbat.stdout.on('data', (data) => {\n console.log(data.toString());\n});\n\nbat.stderr.on('data', (data) => {\n console.error(data.toString());\n});\n\nbat.on('exit', (code) => {\n console.log(`Child exited with code ${code}`);\n});\n
\n// OR...\nconst { exec, spawn } = require('node:child_process');\nexec('my.bat', (err, stdout, stderr) => {\n if (err) {\n console.error(err);\n return;\n }\n console.log(stdout);\n});\n\n// Script with spaces in the filename:\nconst bat = spawn('\"my script.cmd\"', ['a', 'b'], { shell: true });\n// or:\nexec('\"my script.cmd\" a b', (err, stdout, stderr) => {\n // ...\n});\n
",
"type": "module",
"displayName": "Spawning `.bat` and `.cmd` files on Windows"
}
],
"methods": [
{
"textRaw": "`child_process.exec(command[, options][, callback])`",
"type": "method",
"name": "exec",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": "v15.4.0",
"pr-url": "https://github.com/nodejs/node/pull/36308",
"description": "AbortSignal support was added."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
},
"params": [
{
"textRaw": "`command` {string} The command to run, with space-separated arguments.",
"name": "command",
"type": "string",
"desc": "The command to run, with space-separated arguments."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process. **Default:** `process.cwd()`.",
"name": "cwd",
"type": "string|URL",
"default": "`process.cwd()`",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
},
{
"textRaw": "`shell` {string} Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.",
"name": "shell",
"type": "string",
"default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows",
"desc": "Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting the child process using an AbortSignal."
},
{
"textRaw": "`timeout` {number} **Default:** `0`",
"name": "timeout",
"type": "number",
"default": "`0`"
},
{
"textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.",
"name": "maxBuffer",
"type": "number",
"default": "`1024 * 1024`",
"desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]."
},
{
"textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`"
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see setuid(2))."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see setgid(2))."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
}
]
},
{
"textRaw": "`callback` {Function} called with the output when process terminates.",
"name": "callback",
"type": "Function",
"desc": "called with the output when process terminates.",
"options": [
{
"textRaw": "`error` {Error}",
"name": "error",
"type": "Error"
},
{
"textRaw": "`stdout` {string|Buffer}",
"name": "stdout",
"type": "string|Buffer"
},
{
"textRaw": "`stderr` {string|Buffer}",
"name": "stderr",
"type": "string|Buffer"
}
]
}
]
}
],
"desc": "Spawns a shell then executes the command
within that shell, buffering any\ngenerated output. The command
string passed to the exec function is processed\ndirectly by the shell and special characters (vary based on\nshell)\nneed to be dealt with accordingly:
const { exec } = require('node:child_process');\n\nexec('\"/path/to/test file/test.sh\" arg1 arg2');\n// Double quotes are used so that the space in the path is not interpreted as\n// a delimiter of multiple arguments.\n\nexec('echo \"The \\\\$HOME variable is $HOME\"');\n// The $HOME variable is escaped in the first instance, but not in the second.\n
\nNever pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.
\nIf a callback
function is provided, it is called with the arguments\n(error, stdout, stderr)
. On success, error
will be null
. On error,\nerror
will be an instance of Error
. The error.code
property will be\nthe exit code of the process. By convention, any exit code other than 0
\nindicates an error. error.signal
will be the signal that terminated the\nprocess.
The stdout
and stderr
arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding
option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding
is 'buffer'
, or an unrecognized character\nencoding, Buffer
objects will be passed to the callback instead.
const { exec } = require('node:child_process');\nexec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {\n if (error) {\n console.error(`exec error: ${error}`);\n return;\n }\n console.log(`stdout: ${stdout}`);\n console.error(`stderr: ${stderr}`);\n});\n
\nIf timeout
is greater than 0
, the parent will send the signal\nidentified by the killSignal
property (the default is 'SIGTERM'
) if the\nchild runs longer than timeout
milliseconds.
Unlike the exec(3)
POSIX system call, child_process.exec()
does not replace\nthe existing process and uses a shell to execute the command.
If this method is invoked as its util.promisify()
ed version, it returns\na Promise
for an Object
with stdout
and stderr
properties. The returned\nChildProcess
instance is attached to the Promise
as a child
property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error
object given in the\ncallback, but with two additional properties stdout
and stderr
.
const util = require('node:util');\nconst exec = util.promisify(require('node:child_process').exec);\n\nasync function lsExample() {\n const { stdout, stderr } = await exec('ls');\n console.log('stdout:', stdout);\n console.error('stderr:', stderr);\n}\nlsExample();\n
\nIf the signal
option is enabled, calling .abort()
on the corresponding\nAbortController
is similar to calling .kill()
on the child process except\nthe error passed to the callback will be an AbortError
:
const { exec } = require('node:child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = exec('grep ssh', { signal }, (error) => {\n console.error(error); // an AbortError\n});\ncontroller.abort();\n
"
},
{
"textRaw": "`child_process.execFile(file[, args][, options][, callback])`",
"type": "method",
"name": "execFile",
"meta": {
"added": [
"v0.1.91"
],
"changes": [
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v15.4.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36308",
"description": "AbortSignal support was added."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
},
"params": [
{
"textRaw": "`file` {string} The name or path of the executable file to run.",
"name": "file",
"type": "string",
"desc": "The name or path of the executable file to run."
},
{
"textRaw": "`args` {string\\[]} List of string arguments.",
"name": "args",
"type": "string\\[]",
"desc": "List of string arguments."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
},
{
"textRaw": "`timeout` {number} **Default:** `0`",
"name": "timeout",
"type": "number",
"default": "`0`"
},
{
"textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.",
"name": "maxBuffer",
"type": "number",
"default": "`1024 * 1024`",
"desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]."
},
{
"textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`"
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see setuid(2))."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see setgid(2))."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
},
{
"textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.",
"name": "windowsVerbatimArguments",
"type": "boolean",
"default": "`false`",
"desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix."
},
{
"textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).",
"name": "shell",
"type": "boolean|string",
"default": "`false` (no shell)",
"desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting the child process using an AbortSignal."
}
]
},
{
"textRaw": "`callback` {Function} Called with the output when process terminates.",
"name": "callback",
"type": "Function",
"desc": "Called with the output when process terminates.",
"options": [
{
"textRaw": "`error` {Error}",
"name": "error",
"type": "Error"
},
{
"textRaw": "`stdout` {string|Buffer}",
"name": "stdout",
"type": "string|Buffer"
},
{
"textRaw": "`stderr` {string|Buffer}",
"name": "stderr",
"type": "string|Buffer"
}
]
}
]
}
],
"desc": "The child_process.execFile()
function is similar to child_process.exec()
\nexcept that it does not spawn a shell by default. Rather, the specified\nexecutable file
is spawned directly as a new process making it slightly more\nefficient than child_process.exec()
.
The same options as child_process.exec()
are supported. Since a shell is\nnot spawned, behaviors such as I/O redirection and file globbing are not\nsupported.
const { execFile } = require('node:child_process');\nconst child = execFile('node', ['--version'], (error, stdout, stderr) => {\n if (error) {\n throw error;\n }\n console.log(stdout);\n});\n
\nThe stdout
and stderr
arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding
option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding
is 'buffer'
, or an unrecognized character\nencoding, Buffer
objects will be passed to the callback instead.
If this method is invoked as its util.promisify()
ed version, it returns\na Promise
for an Object
with stdout
and stderr
properties. The returned\nChildProcess
instance is attached to the Promise
as a child
property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error
object given in the\ncallback, but with two additional properties stdout
and stderr
.
const util = require('node:util');\nconst execFile = util.promisify(require('node:child_process').execFile);\nasync function getVersion() {\n const { stdout } = await execFile('node', ['--version']);\n console.log(stdout);\n}\ngetVersion();\n
\nIf the shell
option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
If the signal
option is enabled, calling .abort()
on the corresponding\nAbortController
is similar to calling .kill()
on the child process except\nthe error passed to the callback will be an AbortError
:
const { execFile } = require('node:child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = execFile('node', ['--version'], { signal }, (error) => {\n console.error(error); // an AbortError\n});\ncontroller.abort();\n
"
},
{
"textRaw": "`child_process.fork(modulePath[, args][, options])`",
"type": "method",
"name": "fork",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": [
"v17.4.0",
"v16.14.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41225",
"description": "The `modulePath` parameter can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v15.13.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37256",
"description": "timeout was added."
},
{
"version": [
"v15.11.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37325",
"description": "killSignal for AbortSignal was added."
},
{
"version": [
"v15.6.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36603",
"description": "AbortSignal support was added."
},
{
"version": [
"v13.2.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30162",
"description": "The `serialization` option is supported now."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10866",
"description": "The `stdio` option can now be a string."
},
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7811",
"description": "The `stdio` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
},
"params": [
{
"textRaw": "`modulePath` {string|URL} The module to run in the child.",
"name": "modulePath",
"type": "string|URL",
"desc": "The module to run in the child."
},
{
"textRaw": "`args` {string\\[]} List of string arguments.",
"name": "args",
"type": "string\\[]",
"desc": "List of string arguments."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).",
"name": "detached",
"type": "boolean",
"desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][])."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`execPath` {string} Executable used to create the child process.",
"name": "execPath",
"type": "string",
"desc": "Executable used to create the child process."
},
{
"textRaw": "`execArgv` {string\\[]} List of string arguments passed to the executable. **Default:** `process.execArgv`.",
"name": "execArgv",
"type": "string\\[]",
"default": "`process.execArgv`",
"desc": "List of string arguments passed to the executable."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see setgid(2))."
},
{
"textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details. **Default:** `'json'`.",
"name": "serialization",
"type": "string",
"default": "`'json'`",
"desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details."
},
{
"textRaw": "`signal` {AbortSignal} Allows closing the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows closing the child process using an AbortSignal."
},
{
"textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`",
"desc": "The signal value to be used when the spawned process will be killed by timeout or abort signal."
},
{
"textRaw": "`silent` {boolean} If `true`, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s [`stdio`][] for more details. **Default:** `false`.",
"name": "silent",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s [`stdio`][] for more details."
},
{
"textRaw": "`stdio` {Array|string} See [`child_process.spawn()`][]'s [`stdio`][]. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`.",
"name": "stdio",
"type": "Array|string",
"desc": "See [`child_process.spawn()`][]'s [`stdio`][]. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`."
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see setuid(2))."
},
{
"textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.",
"name": "windowsVerbatimArguments",
"type": "boolean",
"default": "`false`",
"desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix."
},
{
"textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.",
"name": "timeout",
"type": "number",
"default": "`undefined`",
"desc": "In milliseconds the maximum amount of time the process is allowed to run."
}
]
}
]
}
],
"desc": "The child_process.fork()
method is a special case of\nchild_process.spawn()
used specifically to spawn new Node.js processes.\nLike child_process.spawn()
, a ChildProcess
object is returned. The\nreturned ChildProcess
will have an additional communication channel\nbuilt-in that allows messages to be passed back and forth between the parent and\nchild. See subprocess.send()
for details.
Keep in mind that spawned Node.js child processes are\nindependent of the parent with exception of the IPC communication channel\nthat is established between the two. Each process has its own memory, with\ntheir own V8 instances. Because of the additional resource allocations\nrequired, spawning a large number of child Node.js processes is not\nrecommended.
\nBy default, child_process.fork()
will spawn new Node.js instances using the\nprocess.execPath
of the parent process. The execPath
property in the\noptions
object allows for an alternative execution path to be used.
Node.js processes launched with a custom execPath
will communicate with the\nparent process using the file descriptor (fd) identified using the\nenvironment variable NODE_CHANNEL_FD
on the child process.
Unlike the fork(2)
POSIX system call, child_process.fork()
does not clone the\ncurrent process.
The shell
option available in child_process.spawn()
is not supported by\nchild_process.fork()
and will be ignored if set.
If the signal
option is enabled, calling .abort()
on the corresponding\nAbortController
is similar to calling .kill()
on the child process except\nthe error passed to the callback will be an AbortError
:
if (process.argv[2] === 'child') {\n setTimeout(() => {\n console.log(`Hello from ${process.argv[2]}!`);\n }, 1_000);\n} else {\n const { fork } = require('node:child_process');\n const controller = new AbortController();\n const { signal } = controller;\n const child = fork(__filename, ['child'], { signal });\n child.on('error', (err) => {\n // This will be called with err being an AbortError if the controller aborts\n });\n controller.abort(); // Stops the child process\n}\n
"
},
{
"textRaw": "`child_process.spawn(command[, args][, options])`",
"type": "method",
"name": "spawn",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v15.13.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37256",
"description": "timeout was added."
},
{
"version": [
"v15.11.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37325",
"description": "killSignal for AbortSignal was added."
},
{
"version": [
"v15.5.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36432",
"description": "AbortSignal support was added."
},
{
"version": [
"v13.2.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30162",
"description": "The `serialization` option is supported now."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
},
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7696",
"description": "The `argv0` option is supported now."
},
{
"version": "v5.7.0",
"pr-url": "https://github.com/nodejs/node/pull/4598",
"description": "The `shell` option is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
},
"params": [
{
"textRaw": "`command` {string} The command to run.",
"name": "command",
"type": "string",
"desc": "The command to run."
},
{
"textRaw": "`args` {string\\[]} List of string arguments.",
"name": "args",
"type": "string\\[]",
"desc": "List of string arguments."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.",
"name": "argv0",
"type": "string",
"desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified."
},
{
"textRaw": "`stdio` {Array|string} Child's stdio configuration (see [`options.stdio`][`stdio`]).",
"name": "stdio",
"type": "Array|string",
"desc": "Child's stdio configuration (see [`options.stdio`][`stdio`])."
},
{
"textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).",
"name": "detached",
"type": "boolean",
"desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][])."
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see setuid(2))."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see setgid(2))."
},
{
"textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details. **Default:** `'json'`.",
"name": "serialization",
"type": "string",
"default": "`'json'`",
"desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details."
},
{
"textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).",
"name": "shell",
"type": "boolean|string",
"default": "`false` (no shell)",
"desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]."
},
{
"textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.",
"name": "windowsVerbatimArguments",
"type": "boolean",
"default": "`false`",
"desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting the child process using an AbortSignal."
},
{
"textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.",
"name": "timeout",
"type": "number",
"default": "`undefined`",
"desc": "In milliseconds the maximum amount of time the process is allowed to run."
},
{
"textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`",
"desc": "The signal value to be used when the spawned process will be killed by timeout or abort signal."
}
]
}
]
}
],
"desc": "The child_process.spawn()
method spawns a new process using the given\ncommand
, with command-line arguments in args
. If omitted, args
defaults\nto an empty array.
If the shell
option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
A third argument may be used to specify additional options, with these defaults:
\nconst defaults = {\n cwd: undefined,\n env: process.env,\n};\n
\nUse cwd
to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory. If given,\nbut the path does not exist, the child process emits an ENOENT
error\nand exits immediately. ENOENT
is also emitted when the command\ndoes not exist.
Use env
to specify environment variables that will be visible to the new\nprocess, the default is process.env
.
undefined
values in env
will be ignored.
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the\nexit code:
const { spawn } = require('node:child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n
\nExample: A very elaborate way to run ps ax | grep ssh
const { spawn } = require('node:child_process');\nconst ps = spawn('ps', ['ax']);\nconst grep = spawn('grep', ['ssh']);\n\nps.stdout.on('data', (data) => {\n grep.stdin.write(data);\n});\n\nps.stderr.on('data', (data) => {\n console.error(`ps stderr: ${data}`);\n});\n\nps.on('close', (code) => {\n if (code !== 0) {\n console.log(`ps process exited with code ${code}`);\n }\n grep.stdin.end();\n});\n\ngrep.stdout.on('data', (data) => {\n console.log(data.toString());\n});\n\ngrep.stderr.on('data', (data) => {\n console.error(`grep stderr: ${data}`);\n});\n\ngrep.on('close', (code) => {\n if (code !== 0) {\n console.log(`grep process exited with code ${code}`);\n }\n});\n
\nExample of checking for failed spawn
:
const { spawn } = require('node:child_process');\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n console.error('Failed to start subprocess.');\n});\n
\nCertain platforms (macOS, Linux) will use the value of argv[0]
for the process\ntitle while others (Windows, SunOS) will use command
.
Node.js overwrites argv[0]
with process.execPath
on startup, so\nprocess.argv[0]
in a Node.js child process will not match the argv0
\nparameter passed to spawn
from the parent. Retrieve it with the\nprocess.argv0
property instead.
If the signal
option is enabled, calling .abort()
on the corresponding\nAbortController
is similar to calling .kill()
on the child process except\nthe error passed to the callback will be an AbortError
:
const { spawn } = require('node:child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst grep = spawn('grep', ['ssh'], { signal });\ngrep.on('error', (err) => {\n // This will be called with err being an AbortError if the controller aborts\n});\ncontroller.abort(); // Stops the child process\n
",
"properties": [
{
"textRaw": "`options.detached`",
"name": "detached",
"meta": {
"added": [
"v0.7.10"
],
"changes": []
},
"desc": "On Windows, setting options.detached
to true
makes it possible for the\nchild process to continue running after the parent exits. The child will have\nits own console window. Once enabled for a child process, it cannot be\ndisabled.
On non-Windows platforms, if options.detached
is set to true
, the child\nprocess will be made the leader of a new process group and session. Child\nprocesses may continue running after the parent exits regardless of whether\nthey are detached or not. See setsid(2)
for more information.
By default, the parent will wait for the detached child to exit. To prevent the\nparent from waiting for a given subprocess
to exit, use the\nsubprocess.unref()
method. Doing so will cause the parent's event loop to not\ninclude the child in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent.
When using the detached
option to start a long-running process, the process\nwill not stay running in the background after the parent exits unless it is\nprovided with a stdio
configuration that is not connected to the parent.\nIf the parent's stdio
is inherited, the child will remain attached to the\ncontrolling terminal.
Example of a long-running process, by detaching and also ignoring its parent\nstdio
file descriptors, in order to ignore the parent's termination:
const { spawn } = require('node:child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\n
\nAlternatively one can redirect the child process' output into files:
\nconst fs = require('node:fs');\nconst { spawn } = require('node:child_process');\nconst out = fs.openSync('./out.log', 'a');\nconst err = fs.openSync('./out.log', 'a');\n\nconst subprocess = spawn('prg', [], {\n detached: true,\n stdio: [ 'ignore', out, err ],\n});\n\nsubprocess.unref();\n
"
},
{
"textRaw": "`options.stdio`",
"name": "stdio",
"meta": {
"added": [
"v0.7.10"
],
"changes": [
{
"version": [
"v15.6.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/29412",
"description": "Added the `overlapped` stdio flag."
},
{
"version": "v3.3.1",
"pr-url": "https://github.com/nodejs/node/pull/2727",
"description": "The value `0` is now accepted as a file descriptor."
}
]
},
"desc": "The options.stdio
option is used to configure the pipes that are established\nbetween the parent and child process. By default, the child's stdin, stdout,\nand stderr are redirected to corresponding subprocess.stdin
,\nsubprocess.stdout
, and subprocess.stderr
streams on the\nChildProcess
object. This is equivalent to setting the options.stdio
\nequal to ['pipe', 'pipe', 'pipe']
.
For convenience, options.stdio
may be one of the following strings:
'pipe'
: equivalent to ['pipe', 'pipe', 'pipe']
(the default)'overlapped'
: equivalent to ['overlapped', 'overlapped', 'overlapped']
'ignore'
: equivalent to ['ignore', 'ignore', 'ignore']
'inherit'
: equivalent to ['inherit', 'inherit', 'inherit']
or [0, 1, 2]
Otherwise, the value of options.stdio
is an array where each index corresponds\nto an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,\nand stderr, respectively. Additional fds can be specified to create additional\npipes between the parent and child. The value is one of the following:
'pipe'
: Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process
object as subprocess.stdio[fd]
. Pipes\ncreated for fds 0, 1, and 2 are also available as subprocess.stdin
,\nsubprocess.stdout
and subprocess.stderr
, respectively.\nThese are not actual Unix pipes and therefore the child process\ncan not use them by their descriptor files,\ne.g. /dev/fd/2
or /dev/stdout
.
'overlapped'
: Same as 'pipe'
except that the FILE_FLAG_OVERLAPPED
flag\nis set on the handle. This is necessary for overlapped I/O on the child\nprocess's stdio handles. See the\ndocs\nfor more details. This is exactly the same as 'pipe'
on non-Windows\nsystems.
'ipc'
: Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess
may have at most one IPC\nstdio file descriptor. Setting this option enables the\nsubprocess.send()
method. If the child is a Node.js process, the\npresence of an IPC channel will enable process.send()
and\nprocess.disconnect()
methods, as well as 'disconnect'
and\n'message'
events within the child.
Accessing the IPC channel fd in any way other than process.send()
\nor using the IPC channel with a child process that is not a Node.js instance\nis not supported.
'ignore'
: Instructs Node.js to ignore the fd in the child. While Node.js\nwill always open fds 0, 1, and 2 for the processes it spawns, setting the fd\nto 'ignore'
will cause Node.js to open /dev/null
and attach it to the\nchild's fd.
'inherit'
: Pass through the corresponding stdio stream to/from the\nparent process. In the first three positions, this is equivalent to\nprocess.stdin
, process.stdout
, and process.stderr
, respectively. In\nany other position, equivalent to 'ignore'
.
<Stream> object: Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that\ncorresponds to the index in the stdio
array. The stream must have an\nunderlying descriptor (file streams do not start until the 'open'
event has\noccurred).
Positive integer: The integer value is interpreted as a file descriptor\nthat is open in the parent process. It is shared with the child\nprocess, similar to how <Stream> objects can be shared. Passing sockets\nis not supported on Windows.
\nnull
, undefined
: Use default value. For stdio fds 0, 1, and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'
.
const { spawn } = require('node:child_process');\n\n// Child will use parent's stdios.\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr.\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs presenting a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });\n
\nIt is worth noting that when an IPC channel is established between the\nparent and child processes, and the child is a Node.js process, the child\nis launched with the IPC channel unreferenced (using unref()
) until the\nchild registers an event handler for the 'disconnect'
event\nor the 'message'
event. This allows the child to exit\nnormally without the process being held open by the open IPC channel.
See also: child_process.exec()
and child_process.fork()
.
The child_process.spawnSync()
, child_process.execSync()
, and\nchild_process.execFileSync()
methods are synchronous and will block the\nNode.js event loop, pausing execution of any additional code until the spawned\nprocess exits.
Blocking calls like these are mostly useful for simplifying general-purpose\nscripting tasks and for simplifying the loading/processing of application\nconfiguration at startup.
", "methods": [ { "textRaw": "`child_process.execFileSync(file[, args][, options])`", "type": "method", "name": "execFileSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": [ "v16.4.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/38862", "description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22409", "description": "The `input` option can now be any `TypedArray` or a `DataView`." }, { "version": "v8.8.0", "pr-url": "https://github.com/nodejs/node/pull/15380", "description": "The `windowsHide` option is supported now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10653", "description": "The `input` option can now be a `Uint8Array`." }, { "version": [ "v6.2.1", "v4.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/6939", "description": "The `encoding` option can now explicitly be set to `buffer`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer|string} The stdout from the command.", "name": "return", "type": "Buffer|string", "desc": "The stdout from the command." }, "params": [ { "textRaw": "`file` {string} The name or path of the executable file to run.", "name": "file", "type": "string", "desc": "The name or path of the executable file to run." }, { "textRaw": "`args` {string\\[]} List of string arguments.", "name": "args", "type": "string\\[]", "desc": "List of string arguments." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cwd` {string|URL} Current working directory of the child process.", "name": "cwd", "type": "string|URL", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`.", "name": "input", "type": "string|Buffer|TypedArray|DataView", "desc": "The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.", "name": "stdio", "type": "string|Array", "default": "`'pipe'`", "desc": "Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified." }, { "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "Environment key-value pairs." }, { "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", "name": "uid", "type": "number", "desc": "Sets the user identity of the process (see setuid(2))." }, { "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", "name": "gid", "type": "number", "desc": "Sets the group identity of the process (see setgid(2))." }, { "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", "name": "timeout", "type": "number", "default": "`undefined`", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", "name": "killSignal", "type": "string|integer", "default": "`'SIGTERM'`", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", "name": "maxBuffer", "type": "number", "default": "`1024 * 1024`", "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at [`maxBuffer` and Unicode][]." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", "name": "encoding", "type": "string", "default": "`'buffer'`", "desc": "The encoding used for all stdio inputs and outputs." }, { "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", "name": "windowsHide", "type": "boolean", "default": "`false`", "desc": "Hide the subprocess console window that would normally be created on Windows systems." }, { "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", "name": "shell", "type": "boolean|string", "default": "`false` (no shell)", "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." } ] } ] } ], "desc": "The child_process.execFileSync()
method is generally identical to\nchild_process.execFile()
with the exception that the method will not\nreturn until the child process has fully closed. When a timeout has been\nencountered and killSignal
is sent, the method won't return until the process\nhas completely exited.
If the child process intercepts and handles the SIGTERM
signal and\ndoes not exit, the parent process will still wait until the child process has\nexited.
If the process times out or has a non-zero exit code, this method will throw an\nError
that will include the full result of the underlying\nchild_process.spawnSync()
.
If the shell
option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
The child_process.execSync()
method is generally identical to\nchild_process.exec()
with the exception that the method will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal
is sent, the method won't return until the process has\ncompletely exited. If the child process intercepts and handles the SIGTERM
\nsignal and doesn't exit, the parent process will wait until the child process\nhas exited.
If the process times out or has a non-zero exit code, this method will throw.\nThe Error
object will contain the entire result from\nchild_process.spawnSync()
.
Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.
" }, { "textRaw": "`child_process.spawnSync(command[, args][, options])`", "type": "method", "name": "spawnSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": [ "v16.4.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/38862", "description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22409", "description": "The `input` option can now be any `TypedArray` or a `DataView`." }, { "version": "v8.8.0", "pr-url": "https://github.com/nodejs/node/pull/15380", "description": "The `windowsHide` option is supported now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10653", "description": "The `input` option can now be a `Uint8Array`." }, { "version": [ "v6.2.1", "v4.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/6939", "description": "The `encoding` option can now explicitly be set to `buffer`." }, { "version": "v5.7.0", "pr-url": "https://github.com/nodejs/node/pull/4598", "description": "The `shell` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`pid` {number} Pid of the child process.", "name": "pid", "type": "number", "desc": "Pid of the child process." }, { "textRaw": "`output` {Array} Array of results from stdio output.", "name": "output", "type": "Array", "desc": "Array of results from stdio output." }, { "textRaw": "`stdout` {Buffer|string} The contents of `output[1]`.", "name": "stdout", "type": "Buffer|string", "desc": "The contents of `output[1]`." }, { "textRaw": "`stderr` {Buffer|string} The contents of `output[2]`.", "name": "stderr", "type": "Buffer|string", "desc": "The contents of `output[2]`." }, { "textRaw": "`status` {number|null} The exit code of the subprocess, or `null` if the subprocess terminated due to a signal.", "name": "status", "type": "number|null", "desc": "The exit code of the subprocess, or `null` if the subprocess terminated due to a signal." }, { "textRaw": "`signal` {string|null} The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal.", "name": "signal", "type": "string|null", "desc": "The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal." }, { "textRaw": "`error` {Error} The error object if the child process failed or timed out.", "name": "error", "type": "Error", "desc": "The error object if the child process failed or timed out." } ] }, "params": [ { "textRaw": "`command` {string} The command to run.", "name": "command", "type": "string", "desc": "The command to run." }, { "textRaw": "`args` {string\\[]} List of string arguments.", "name": "args", "type": "string\\[]", "desc": "List of string arguments." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cwd` {string|URL} Current working directory of the child process.", "name": "cwd", "type": "string|URL", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`.", "name": "input", "type": "string|Buffer|TypedArray|DataView", "desc": "The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`." }, { "textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.", "name": "argv0", "type": "string", "desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. **Default:** `'pipe'`.", "name": "stdio", "type": "string|Array", "default": "`'pipe'`", "desc": "Child's stdio configuration." }, { "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "Environment key-value pairs." }, { "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", "name": "uid", "type": "number", "desc": "Sets the user identity of the process (see setuid(2))." }, { "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", "name": "gid", "type": "number", "desc": "Sets the group identity of the process (see setgid(2))." }, { "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", "name": "timeout", "type": "number", "default": "`undefined`", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", "name": "killSignal", "type": "string|integer", "default": "`'SIGTERM'`", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", "name": "maxBuffer", "type": "number", "default": "`1024 * 1024`", "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", "name": "encoding", "type": "string", "default": "`'buffer'`", "desc": "The encoding used for all stdio inputs and outputs." }, { "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", "name": "shell", "type": "boolean|string", "default": "`false` (no shell)", "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." }, { "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.", "name": "windowsVerbatimArguments", "type": "boolean", "default": "`false`", "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD." }, { "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", "name": "windowsHide", "type": "boolean", "default": "`false`", "desc": "Hide the subprocess console window that would normally be created on Windows systems." } ] } ] } ], "desc": "The child_process.spawnSync()
method is generally identical to\nchild_process.spawn()
with the exception that the function will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal
is sent, the method won't return until the process has\ncompletely exited. If the process intercepts and handles the SIGTERM
signal\nand doesn't exit, the parent process will wait until the child process has\nexited.
If the shell
option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
The maxBuffer
option specifies the largest number of bytes allowed on stdout
\nor stderr
. If this value is exceeded, then the child process is terminated.\nThis impacts output that includes multibyte character encodings such as UTF-8 or\nUTF-16. For instance, console.log('中文测试')
will send 13 UTF-8 encoded bytes\nto stdout
although there are only 4 characters.
The shell should understand the -c
switch. If the shell is 'cmd.exe'
, it\nshould understand the /d /s /c
switches and command-line parsing should be\ncompatible.
Although Microsoft specifies %COMSPEC%
must contain the path to\n'cmd.exe'
in the root environment, child processes are not always subject to\nthe same requirement. Thus, in child_process
functions where a shell can be\nspawned, 'cmd.exe'
is used as a fallback if process.env.ComSpec
is\nunavailable.
Child processes support a serialization mechanism for IPC that is based on the\nserialization API of the node:v8
module, based on the\nHTML structured clone algorithm. This is generally more powerful and\nsupports more built-in JavaScript object types, such as BigInt
, Map
\nand Set
, ArrayBuffer
and TypedArray
, Buffer
, Error
, RegExp
etc.
However, this format is not a full superset of JSON, and e.g. properties set on\nobjects of such built-in types will not be passed on through the serialization\nstep. Additionally, performance may not be equivalent to that of JSON, depending\non the structure of the passed data.\nTherefore, this feature requires opting in by setting the\nserialization
option to 'advanced'
when calling child_process.spawn()
\nor child_process.fork()
.
Instances of the ChildProcess
represent spawned child processes.
Instances of ChildProcess
are not intended to be created directly. Rather,\nuse the child_process.spawn()
, child_process.exec()
,\nchild_process.execFile()
, or child_process.fork()
methods to create\ninstances of ChildProcess
.
The 'close'
event is emitted after a process has ended and the stdio\nstreams of a child process have been closed. This is distinct from the\n'exit'
event, since multiple processes might share the same stdio\nstreams. The 'close'
event will always emit after 'exit'
was\nalready emitted, or 'error'
if the child failed to spawn.
const { spawn } = require('node:child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process close all stdio with code ${code}`);\n});\n\nls.on('exit', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n
"
},
{
"textRaw": "Event: `'disconnect'`",
"type": "event",
"name": "disconnect",
"meta": {
"added": [
"v0.7.2"
],
"changes": []
},
"params": [],
"desc": "The 'disconnect'
event is emitted after calling the\nsubprocess.disconnect()
method in parent process or\nprocess.disconnect()
in child process. After disconnecting it is no longer\npossible to send or receive messages, and the subprocess.connected
\nproperty is false
.
The 'error'
event is emitted whenever:
signal
option.The 'exit'
event may or may not fire after an error has occurred. When\nlistening to both the 'exit'
and 'error'
events, guard\nagainst accidentally invoking handler functions multiple times.
See also subprocess.kill()
and subprocess.send()
.
The 'exit'
event is emitted after the child process ends. If the process\nexited, code
is the final exit code of the process, otherwise null
. If the\nprocess terminated due to receipt of a signal, signal
is the string name of\nthe signal, otherwise null
. One of the two will always be non-null
.
When the 'exit'
event is triggered, child process stdio streams might still be\nopen.
Node.js establishes signal handlers for SIGINT
and SIGTERM
and Node.js\nprocesses will not terminate immediately due to receipt of those signals.\nRather, Node.js will perform a sequence of cleanup actions and then will\nre-raise the handled signal.
See waitpid(2)
.
The 'message'
event is triggered when a child process uses\nprocess.send()
to send messages.
The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.
\nIf the serialization
option was set to 'advanced'
used when spawning the\nchild process, the message
argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for more details.
The 'spawn'
event is emitted once the child process has spawned successfully.\nIf the child process does not spawn successfully, the 'spawn'
event is not\nemitted and the 'error'
event is emitted instead.
If emitted, the 'spawn'
event comes before all other events and before any\ndata is received via stdout
or stderr
.
The 'spawn'
event will fire regardless of whether an error occurs within\nthe spawned process. For example, if bash some-command
spawns successfully,\nthe 'spawn'
event will fire, though bash
may fail to spawn some-command
.\nThis caveat also applies when using { shell: true }
.
The subprocess.channel
property is a reference to the child's IPC channel. If\nno IPC channel exists, this property is undefined
.
This method makes the IPC channel keep the event loop of the parent process\nrunning if .unref()
has been called before.
This method makes the IPC channel not keep the event loop of the parent process\nrunning, and lets it finish even while the channel is open.
" } ] }, { "textRaw": "`connected` {boolean} Set to `false` after `subprocess.disconnect()` is called.", "type": "boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "desc": "The subprocess.connected
property indicates whether it is still possible to\nsend and receive messages from a child process. When subprocess.connected
is\nfalse
, it is no longer possible to send or receive messages.
The subprocess.exitCode
property indicates the exit code of the child process.\nIf the child process is still running, the field will be null
.
The subprocess.killed
property indicates whether the child process\nsuccessfully received a signal from subprocess.kill()
. The killed
property\ndoes not indicate that the child process has been terminated.
Returns the process identifier (PID) of the child process. If the child process\nfails to spawn due to errors, then the value is undefined
and error
is\nemitted.
const { spawn } = require('node:child_process');\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n
"
},
{
"textRaw": "`signalCode` {string|null}",
"type": "string|null",
"name": "signalCode",
"desc": "The subprocess.signalCode
property indicates the signal received by\nthe child process if any, else null
.
The subprocess.spawnargs
property represents the full list of command-line\narguments the child process was launched with.
The subprocess.spawnfile
property indicates the executable file name of\nthe child process that is launched.
For child_process.fork()
, its value will be equal to\nprocess.execPath
.\nFor child_process.spawn()
, its value will be the name of\nthe executable file.\nFor child_process.exec()
, its value will be the name of the shell\nin which the child process is launched.
A Readable Stream
that represents the child process's stderr
.
If the child was spawned with stdio[2]
set to anything other than 'pipe'
,\nthen this will be null
.
subprocess.stderr
is an alias for subprocess.stdio[2]
. Both properties will\nrefer to the same value.
The subprocess.stderr
property can be null
or undefined
\nif the child process could not be successfully spawned.
A Writable Stream
that represents the child process's stdin
.
If a child process waits to read all of its input, the child will not continue\nuntil this stream has been closed via end()
.
If the child was spawned with stdio[0]
set to anything other than 'pipe'
,\nthen this will be null
.
subprocess.stdin
is an alias for subprocess.stdio[0]
. Both properties will\nrefer to the same value.
The subprocess.stdin
property can be null
or undefined
\nif the child process could not be successfully spawned.
A sparse array of pipes to the child process, corresponding with positions in\nthe stdio
option passed to child_process.spawn()
that have been set\nto the value 'pipe'
. subprocess.stdio[0]
, subprocess.stdio[1]
, and\nsubprocess.stdio[2]
are also available as subprocess.stdin
,\nsubprocess.stdout
, and subprocess.stderr
, respectively.
In the following example, only the child's fd 1
(stdout) is configured as a\npipe, so only the parent's subprocess.stdio[1]
is a stream, all other values\nin the array are null
.
const assert = require('node:assert');\nconst fs = require('node:fs');\nconst child_process = require('node:child_process');\n\nconst subprocess = child_process.spawn('ls', {\n stdio: [\n 0, // Use parent's stdin for child.\n 'pipe', // Pipe child's stdout to parent.\n fs.openSync('err.out', 'w'), // Direct child's stderr to a file.\n ],\n});\n\nassert.strictEqual(subprocess.stdio[0], null);\nassert.strictEqual(subprocess.stdio[0], subprocess.stdin);\n\nassert(subprocess.stdout);\nassert.strictEqual(subprocess.stdio[1], subprocess.stdout);\n\nassert.strictEqual(subprocess.stdio[2], null);\nassert.strictEqual(subprocess.stdio[2], subprocess.stderr);\n
\nThe subprocess.stdio
property can be undefined
if the child process could\nnot be successfully spawned.
A Readable Stream
that represents the child process's stdout
.
If the child was spawned with stdio[1]
set to anything other than 'pipe'
,\nthen this will be null
.
subprocess.stdout
is an alias for subprocess.stdio[1]
. Both properties will\nrefer to the same value.
const { spawn } = require('node:child_process');\n\nconst subprocess = spawn('ls');\n\nsubprocess.stdout.on('data', (data) => {\n console.log(`Received chunk ${data}`);\n});\n
\nThe subprocess.stdout
property can be null
or undefined
\nif the child process could not be successfully spawned.
Closes the IPC channel between parent and child, allowing the child to exit\ngracefully once there are no other connections keeping it alive. After calling\nthis method the subprocess.connected
and process.connected
properties in\nboth the parent and child (respectively) will be set to false
, and it will be\nno longer possible to pass messages between the processes.
The 'disconnect'
event will be emitted when there are no messages in the\nprocess of being received. This will most often be triggered immediately after\ncalling subprocess.disconnect()
.
When the child process is a Node.js instance (e.g. spawned using\nchild_process.fork()
), the process.disconnect()
method can be invoked\nwithin the child process to close the IPC channel as well.
The subprocess.kill()
method sends a signal to the child process. If no\nargument is given, the process will be sent the 'SIGTERM'
signal. See\nsignal(7)
for a list of available signals. This function returns true
if\nkill(2)
succeeds, and false
otherwise.
const { spawn } = require('node:child_process');\nconst grep = spawn('grep', ['ssh']);\n\ngrep.on('close', (code, signal) => {\n console.log(\n `child process terminated due to receipt of signal ${signal}`);\n});\n\n// Send SIGHUP to process.\ngrep.kill('SIGHUP');\n
\nThe ChildProcess
object may emit an 'error'
event if the signal\ncannot be delivered. Sending a signal to a child process that has already exited\nis not an error but may have unforeseen consequences. Specifically, if the\nprocess identifier (PID) has been reassigned to another process, the signal will\nbe delivered to that process instead which can have unexpected results.
While the function is called kill
, the signal delivered to the child process\nmay not actually terminate the process.
See kill(2)
for reference.
On Windows, where POSIX signals do not exist, the signal
argument will be\nignored, and the process will be killed forcefully and abruptly (similar to\n'SIGKILL'
).\nSee Signal Events for more details.
On Linux, child processes of child processes will not be terminated\nwhen attempting to kill their parent. This is likely to happen when running a\nnew process in a shell or with the use of the shell
option of ChildProcess
:
'use strict';\nconst { spawn } = require('node:child_process');\n\nconst subprocess = spawn(\n 'sh',\n [\n '-c',\n `node -e \"setInterval(() => {\n console.log(process.pid, 'is alive')\n }, 500);\"`,\n ], {\n stdio: ['inherit', 'inherit', 'inherit'],\n },\n);\n\nsetTimeout(() => {\n subprocess.kill(); // Does not terminate the Node.js process in the shell.\n}, 2000);\n
"
},
{
"textRaw": "`subprocess[Symbol.dispose]()`",
"type": "method",
"name": "[Symbol.dispose]",
"meta": {
"added": [
"v20.5.0",
"v18.18.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": []
}
],
"desc": "Calls subprocess.kill()
with 'SIGTERM'
.
Calling subprocess.ref()
after making a call to subprocess.unref()
will\nrestore the removed reference count for the child process, forcing the parent\nto wait for the child to exit before exiting itself.
const { spawn } = require('node:child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\nsubprocess.ref();\n
"
},
{
"textRaw": "`subprocess.send(message[, sendHandle[, options]][, callback])`",
"type": "method",
"name": "send",
"meta": {
"added": [
"v0.5.9"
],
"changes": [
{
"version": "v5.8.0",
"pr-url": "https://github.com/nodejs/node/pull/5283",
"description": "The `options` parameter, and the `keepOpen` option in particular, is supported now."
},
{
"version": "v5.0.0",
"pr-url": "https://github.com/nodejs/node/pull/3516",
"description": "This method returns a boolean for flow control now."
},
{
"version": "v4.0.0",
"pr-url": "https://github.com/nodejs/node/pull/2620",
"description": "The `callback` parameter is supported now."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
},
"params": [
{
"textRaw": "`message` {Object}",
"name": "message",
"type": "Object"
},
{
"textRaw": "`sendHandle` {Handle}",
"name": "sendHandle",
"type": "Handle"
},
{
"textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
"name": "options",
"type": "Object",
"desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
"options": [
{
"textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.",
"name": "keepOpen",
"type": "boolean",
"default": "`false`",
"desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process."
}
]
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function"
}
]
}
],
"desc": "When an IPC channel has been established between the parent and child (\ni.e. when using child_process.fork()
), the subprocess.send()
method can\nbe used to send messages to the child process. When the child process is a\nNode.js instance, these messages can be received via the 'message'
event.
The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.
\nFor example, in the parent script:
\nconst cp = require('node:child_process');\nconst n = cp.fork(`${__dirname}/sub.js`);\n\nn.on('message', (m) => {\n console.log('PARENT got message:', m);\n});\n\n// Causes the child to print: CHILD got message: { hello: 'world' }\nn.send({ hello: 'world' });\n
\nAnd then the child script, 'sub.js'
might look like this:
process.on('message', (m) => {\n console.log('CHILD got message:', m);\n});\n\n// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }\nprocess.send({ foo: 'bar', baz: NaN });\n
\nChild Node.js processes will have a process.send()
method of their own\nthat allows the child to send messages back to the parent.
There is a special case when sending a {cmd: 'NODE_foo'}
message. Messages\ncontaining a NODE_
prefix in the cmd
property are reserved for use within\nNode.js core and will not be emitted in the child's 'message'
\nevent. Rather, such messages are emitted using the\n'internalMessage'
event and are consumed internally by Node.js.\nApplications should avoid using such messages or listening for\n'internalMessage'
events as it is subject to change without notice.
The optional sendHandle
argument that may be passed to subprocess.send()
is\nfor passing a TCP server or socket object to the child process. The child will\nreceive the object as the second argument passed to the callback function\nregistered on the 'message'
event. Any data that is received\nand buffered in the socket will not be sent to the child.
The optional callback
is a function that is invoked after the message is\nsent but before the child may have received it. The function is called with a\nsingle argument: null
on success, or an Error
object on failure.
If no callback
function is provided and the message cannot be sent, an\n'error'
event will be emitted by the ChildProcess
object. This can\nhappen, for instance, when the child process has already exited.
subprocess.send()
will return false
if the channel has closed or when the\nbacklog of unsent messages exceeds a threshold that makes it unwise to send\nmore. Otherwise, the method returns true
. The callback
function can be\nused to implement flow control.
The sendHandle
argument can be used, for instance, to pass the handle of\na TCP server object to the child process as illustrated in the example below:
const subprocess = require('node:child_process').fork('subprocess.js');\n\n// Open up the server object and send the handle.\nconst server = require('node:net').createServer();\nserver.on('connection', (socket) => {\n socket.end('handled by parent');\n});\nserver.listen(1337, () => {\n subprocess.send('server', server);\n});\n
\nThe child would then receive the server object as:
\nprocess.on('message', (m, server) => {\n if (m === 'server') {\n server.on('connection', (socket) => {\n socket.end('handled by child');\n });\n }\n});\n
\nOnce the server is now shared between the parent and child, some connections\ncan be handled by the parent and some by the child.
\nWhile the example above uses a server created using the node:net
module,\nnode:dgram
module servers use exactly the same workflow with the exceptions of\nlistening on a 'message'
event instead of 'connection'
and using\nserver.bind()
instead of server.listen()
. This is, however, only\nsupported on Unix platforms.
Similarly, the sendHandler
argument can be used to pass the handle of a\nsocket to the child process. The example below spawns two children that each\nhandle connections with \"normal\" or \"special\" priority:
const { fork } = require('node:child_process');\nconst normal = fork('subprocess.js', ['normal']);\nconst special = fork('subprocess.js', ['special']);\n\n// Open up the server and send sockets to child. Use pauseOnConnect to prevent\n// the sockets from being read before they are sent to the child process.\nconst server = require('node:net').createServer({ pauseOnConnect: true });\nserver.on('connection', (socket) => {\n\n // If this is special priority...\n if (socket.remoteAddress === '74.125.127.100') {\n special.send('socket', socket);\n return;\n }\n // This is normal priority.\n normal.send('socket', socket);\n});\nserver.listen(1337);\n
\nThe subprocess.js
would receive the socket handle as the second argument\npassed to the event callback function:
process.on('message', (m, socket) => {\n if (m === 'socket') {\n if (socket) {\n // Check that the client socket exists.\n // It is possible for the socket to be closed between the time it is\n // sent and the time it is received in the child process.\n socket.end(`Request handled with ${process.argv[2]} priority`);\n }\n }\n});\n
\nDo not use .maxConnections
on a socket that has been passed to a subprocess.\nThe parent cannot track when the socket is destroyed.
Any 'message'
handlers in the subprocess should verify that socket
exists,\nas the connection may have been closed during the time it takes to send the\nconnection to the child.
By default, the parent will wait for the detached child to exit. To prevent the\nparent from waiting for a given subprocess
to exit, use the\nsubprocess.unref()
method. Doing so will cause the parent's event loop to not\ninclude the child in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent.
const { spawn } = require('node:child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\n
"
}
]
}
],
"type": "module",
"displayName": "Child process"
}
]
}