{ "source": "doc/api/child_process.markdown", "modules": [ { "textRaw": "Child Process", "name": "child_process", "stability": 2, "stabilityText": "Stable", "desc": "

Node.js provides a tri-directional popen(3) facility through the\nchild_process module.\n\n

\n

It is possible to stream data through a child's stdin, stdout, and\nstderr in a fully non-blocking way. (Note that some programs use\nline-buffered I/O internally. That doesn't affect Node.js but it means\ndata you send to the child process may not be immediately consumed.)\n\n

\n

To create a child process use require('child_process').spawn() or\nrequire('child_process').fork(). The semantics of each are slightly\ndifferent, and explained [below][].\n\n

\n

For scripting purposes you may find the [synchronous counterparts][] more\nconvenient.\n\n

\n", "classes": [ { "textRaw": "Class: ChildProcess", "type": "class", "name": "ChildProcess", "desc": "

ChildProcess is an [EventEmitter][].\n\n

\n

Child processes always have three streams associated with them. child.stdin,\nchild.stdout, and child.stderr. These may be shared with the stdio\nstreams of the parent process, or they may be separate stream objects\nwhich can be piped to and from.\n\n

\n

The ChildProcess class is not intended to be used directly. Use the\n[spawn()][], [exec()][], [execFile()][], or [fork()][] methods to create\nan instance of ChildProcess.\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "params": [], "desc": "

This event is emitted when the stdio streams of a child process have all\nterminated. This is distinct from 'exit', since multiple processes\nmight share the same stdio streams.\n\n

\n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

This event is emitted after calling the .disconnect() method in the parent\nor in the child. After disconnecting it is no longer possible to send messages,\nand the .connected property is false.\n\n

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted when:\n\n

\n
    \n
  1. The process could not be spawned, or
  2. \n
  3. The process could not be killed, or
  4. \n
  5. Sending a message to the child process failed for whatever reason.
  6. \n
\n

Note that the 'exit' event may or may not fire after an error has occurred. If\nyou are listening on both events to fire a function, remember to guard against\ncalling your function twice.\n\n

\n

See also [ChildProcess#kill()][] and [ChildProcess#send()][].\n\n

\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

This event is emitted after the child process ends. If the process terminated\nnormally, code is the final exit code of the process, otherwise null. If\nthe process terminated due to receipt of a signal, signal is the string name\nof the signal, otherwise null.\n\n

\n

Note that the child process stdio streams might still be open.\n\n

\n

Also, note that Node.js establishes signal handlers for SIGINT and\nSIGTERM, so it will not terminate due to receipt of those signals,\nit will exit.\n\n

\n

See waitpid(2).\n\n

\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

Messages sent by .send(message, [sendHandle]) are obtained using the\n'message' event.\n\n

\n" } ], "properties": [ { "textRaw": "`connected` {Boolean} Set to false after `.disconnect` is called ", "name": "connected", "desc": "

If .connected is false, it is no longer possible to send messages.\n\n

\n", "shortDesc": "Set to false after `.disconnect` is called" }, { "textRaw": "`pid` {Integer} ", "name": "pid", "desc": "

The PID of the child process.\n\n

\n

Example:\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
\n" }, { "textRaw": "`stderr` {Stream object} ", "name": "stderr", "desc": "

A Readable Stream that represents the child process's stderr.\n\n

\n

If the child was not spawned with stdio[2] set to 'pipe', then this will\nnot be set.\n\n

\n

child.stderr is shorthand for child.stdio[2]. Both properties will refer\nto the same object, or null.\n\n

\n" }, { "textRaw": "`stdin` {Stream object} ", "name": "stdin", "desc": "

A Writable Stream that represents the child process's stdin.\nIf the child is waiting to read all its input, it will not continue until this\nstream has been closed via end().\n\n

\n

If the child was not spawned with stdio[0] set to 'pipe', then this will\nnot be set.\n\n

\n

child.stdin is shorthand for child.stdio[0]. Both properties will refer\nto the same object, or null.\n\n

\n" }, { "textRaw": "`stdio` {Array} ", "name": "stdio", "desc": "

A sparse array of pipes to the child process, corresponding with positions in\nthe [stdio][] option to [spawn()][] that have been set to 'pipe'.\nNote that streams 0-2 are also available as ChildProcess.stdin,\nChildProcess.stdout, and ChildProcess.stderr, respectively.\n\n

\n

In the following example, only the child's fd 1 is setup as a pipe, so only\nthe parent's child.stdio[1] is a stream, all other values in the array are\nnull.\n\n

\n
var assert = require('assert');\nvar fs = require('fs');\nvar child_process = require('child_process');\n\nchild = child_process.spawn('ls', {\n    stdio: [\n      0, // use parents 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.equal(child.stdio[0], null);\nassert.equal(child.stdio[0], child.stdin);\n\nassert(child.stdout);\nassert.equal(child.stdio[1], child.stdout);\n\nassert.equal(child.stdio[2], null);\nassert.equal(child.stdio[2], child.stderr);
\n" }, { "textRaw": "`stdout` {Stream object} ", "name": "stdout", "desc": "

A Readable Stream that represents the child process's stdout.\n\n

\n

If the child was not spawned with stdio[1] set to 'pipe', then this will\nnot be set.\n\n

\n

child.stdout is shorthand for child.stdio[1]. Both properties will refer\nto the same object, or null.\n\n

\n" } ], "methods": [ { "textRaw": "child.disconnect()", "type": "method", "name": "disconnect", "desc": "

Close 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 .connected flag will be set to false in both the parent and\nchild, and it is no longer possible to send messages.\n\n

\n

The 'disconnect' event will be emitted when there are no messages in the process\nof being received, most likely immediately.\n\n

\n

Note that you can also call process.disconnect() in the child process when the\nchild process has any open IPC channels with the parent (i.e [fork()][]).\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "child.kill([signal])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} ", "name": "signal", "type": "String", "optional": true } ] }, { "params": [ { "name": "signal", "optional": true } ] } ], "desc": "

Send a signal to the child process. If no argument is given, the process will\nbe sent 'SIGTERM'. See signal(7) for a list of available signals.\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\ngrep.on('close', function (code, signal) {\n  console.log('child process terminated due to receipt of signal ' + signal);\n});\n\n// send SIGHUP to process\ngrep.kill('SIGHUP');
\n

May emit an 'error' event when the signal cannot be delivered. Sending a\nsignal to a child process that has already exited is not an error but may\nhave unforeseen consequences: if the PID (the process ID) has been reassigned\nto another process, the signal will be delivered to that process instead.\nWhat happens next is anyone's guess.\n\n

\n

Note that while the function is called kill, the signal delivered to the\nchild process may not actually kill it. kill really just sends a signal\nto a process.\n\n

\n

See kill(2)\n\n

\n" }, { "textRaw": "child.send(message[, sendHandle][, callback])", "type": "method", "name": "send", "signatures": [ { "return": { "textRaw": "Return: Boolean ", "name": "return", "desc": "Boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

When using [child_process.fork()][] you can write to the child using\nchild.send(message[, sendHandle][, callback]) and messages are received by\na 'message' event on the child.\n\n

\n

For example:\n\n

\n
var cp = require('child_process');\n\nvar n = cp.fork(__dirname + '/sub.js');\n\nn.on('message', function(m) {\n  console.log('PARENT got message:', m);\n});\n\nn.send({ hello: 'world' });
\n

And then the child script, 'sub.js' might look like this:\n\n

\n
process.on('message', function(m) {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\n

In the child the process object will have a send() method, and process\nwill emit objects each time it receives a message on its channel.\n\n

\n

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property will not be emitted in\nthe 'message' event, since they are internal messages used by Node.js core.\nMessages containing the prefix are emitted in the 'internalMessage' event.\nAvoid using this feature; it is subject to change without notice.\n\n

\n

The sendHandle option to child.send() is for sending a TCP server or\nsocket object to another process. The child will receive the object as its\nsecond argument to the 'message' event.\n\n

\n

The callback option is a function that is invoked after the message is\nsent but before the target may have received it. It is called with a single\nargument: null on success, or an [Error][] object on failure.\n\n

\n

child.send() emits an 'error' event if no callback was given and the message\ncannot be sent, for example because the child process has already exited.\n\n

\n

child.send() returns false if the channel has closed or when the backlog of\nunsent messages exceeds a threshold that makes it unwise to send more.\nOtherwise, it returns true. Use the callback mechanism to implement flow\ncontrol.\n\n

\n

Example: sending server object

\n

Here is an example of sending a server:\n\n

\n
var child = require('child_process').fork('child.js');\n\n// Open up the server object and send the handle.\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n  socket.end('handled by parent');\n});\nserver.listen(1337, function() {\n  child.send('server', server);\n});
\n

And the child would then receive the server object as:\n\n

\n
process.on('message', function(m, server) {\n  if (m === 'server') {\n    server.on('connection', function (socket) {\n      socket.end('handled by child');\n    });\n  }\n});
\n

Note that the server is now shared between the parent and child, this means\nthat some connections will be handled by the parent and some by the child.\n\n

\n

For dgram servers the workflow is exactly the same. Here you listen on\na 'message' event instead of 'connection' and use server.bind instead of\nserver.listen. (Currently only supported on UNIX platforms.)\n\n

\n

Example: sending socket object

\n

Here is an example of sending a socket. It will spawn two children and handle\nconnections with the remote address 74.125.127.100 as VIP by sending the\nsocket to a "special" child process. Other sockets will go to a "normal"\nprocess.\n\n

\n
var normal = require('child_process').fork('child.js', ['normal']);\nvar special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n\n  // if this is a VIP\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // just the usual...\n  normal.send('socket', socket);\n});\nserver.listen(1337);
\n

The child.js could look like this:\n\n

\n
process.on('message', function(m, socket) {\n  if (m === 'socket') {\n    socket.end('You were handled as a ' + process.argv[2] + ' person');\n  }\n});
\n

Note that once a single socket has been sent to a child the parent can no\nlonger keep track of when the socket is destroyed. To indicate this condition\nthe .connections property becomes null.\nIt is also recommended not to use .maxConnections in this condition.\n\n

\n" } ] } ], "modules": [ { "textRaw": "Asynchronous Process Creation", "name": "asynchronous_process_creation", "desc": "

These methods follow the common async programming patterns (accepting a\ncallback or returning an EventEmitter).\n\n

\n", "methods": [ { "textRaw": "child_process.exec(command[, options], callback)", "type": "method", "name": "exec", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "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} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`shell` {String} Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`.) ", "name": "shell", "type": "String", "desc": "Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`.)" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: `200*1024`) ", "name": "maxBuffer", "default": "200*1024", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" }, { "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).)" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} called with the output when process terminates ", "options": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error" }, { "textRaw": "`stdout` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates" } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Runs a command in a shell and buffers the output.\n\n

\n
var exec = require('child_process').exec,\n    child;\n\nchild = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});
\n

The callback gets the arguments (error, stdout, stderr). On success, error\nwill be null. On error, error will be an instance of [Error][] and error.code\nwill be the exit code of the child process, and error.signal will be set to the\nsignal that terminated the process.\n\n

\n

There is a second optional argument to specify several options. The\ndefault options are\n\n

\n
{ encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200*1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null }
\n

If timeout is greater than 0, then it will kill the child process\nif it runs longer than timeout milliseconds. The child process is killed with\nkillSignal (default: 'SIGTERM'). maxBuffer specifies the largest\namount of data (in bytes) allowed on stdout or stderr - if this value is\nexceeded then the child process is killed.\n\n

\n

Note: Unlike the exec() POSIX system call, child_process.exec() does not replace\nthe existing process and uses a shell to execute the command.\n\n

\n" }, { "textRaw": "child_process.execFile(file[, args][, options][, callback])", "type": "method", "name": "execFile", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`file` {String} The filename of the program to run ", "name": "file", "type": "String", "desc": "The filename of the program to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: 200\\*1024) ", "name": "maxBuffer", "default": "200\\*1024", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" }, { "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).)" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} called with the output when process terminates ", "options": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error" }, { "textRaw": "`stdout` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

This is similar to [child_process.exec()][] except it does not execute a\nsubshell but rather the specified file directly. This makes it slightly\nleaner than [child_process.exec()][]. It has the same options.\n\n\n

\n" }, { "textRaw": "child_process.fork(modulePath[, args][, options])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`modulePath` {String} The module to run in the child ", "name": "modulePath", "type": "String", "desc": "The module to run in the child" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "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` {Array} List of string arguments passed to the executable (Default: `process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "List of string arguments passed to the executable" }, { "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 [`spawn()`][]'s [`stdio`][] for more details (default is false) ", "name": "silent", "type": "Boolean", "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 [`spawn()`][]'s [`stdio`][] for more details (default is false)" }, { "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).)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "modulePath" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

This is a special case of the [child_process.spawn()][] functionality for\nspawning Node.js processes. In addition to having all the methods in a normal\nChildProcess instance, the returned object has a communication channel built-in.\nSee [ChildProcess#send()][] for details.\n\n

\n

These child Node.js processes are still whole new instances of V8. Assume at\nleast 30ms startup and 10mb memory for each new Node.js. That is, you cannot\ncreate many thousands of them.\n\n

\n

The execPath property in the options object allows for a process to be\ncreated for the child rather than the current node executable. This should be\ndone with care and by default will talk over the fd represented an\nenvironmental variable NODE_CHANNEL_FD on the child process. The input and\noutput on this fd is expected to be line delimited JSON objects.\n\n

\n

Note: Unlike the fork() POSIX system call, [child_process.fork()][] does not clone the\ncurrent process.\n\n

\n" }, { "textRaw": "child_process.spawn(command[, args][, options])", "type": "method", "name": "spawn", "signatures": [ { "return": { "textRaw": "return: {ChildProcess object} ", "name": "return", "type": "ChildProcess object" }, "params": [ { "textRaw": "`command` {String} The command to run ", "name": "command", "type": "String", "desc": "The command to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See [below](#child_process_options_stdio)) ", "name": "stdio", "type": "Array|String", "desc": "Child's stdio configuration. (See [below](#child_process_options_stdio))" }, { "textRaw": "`detached` {Boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [below](#child_process_options_detached)) ", "name": "detached", "type": "Boolean", "desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [below](#child_process_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).)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

Launches a new process with the given command, with command line arguments in\nargs. If omitted, args defaults to an empty Array.\n\n

\n

The third argument is used to specify additional options, with these defaults:\n\n

\n
{ cwd: undefined,\n  env: process.env\n}
\n

Use cwd to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory.\n\n

\n

Use env to specify environment variables that will be visible to the new\nprocess, the default is process.env.\n\n

\n

Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:\n\n

\n
var spawn = require('child_process').spawn,\n    ls    = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', function (data) {\n  console.log('stdout: ' + data);\n});\n\nls.stderr.on('data', function (data) {\n  console.log('stderr: ' + data);\n});\n\nls.on('close', function (code) {\n  console.log('child process exited with code ' + code);\n});
\n

Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

\n
var spawn = require('child_process').spawn,\n    ps    = spawn('ps', ['ax']),\n    grep  = spawn('grep', ['ssh']);\n\nps.stdout.on('data', function (data) {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', function (data) {\n  console.log('ps stderr: ' + data);\n});\n\nps.on('close', function (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', function (data) {\n  console.log('' + data);\n});\n\ngrep.stderr.on('data', function (data) {\n  console.log('grep stderr: ' + data);\n});\n\ngrep.on('close', function (code) {\n  if (code !== 0) {\n    console.log('grep process exited with code ' + code);\n  }\n});
\n

Example of checking for failed exec:\n\n

\n
var spawn = require('child_process').spawn,\n    child = spawn('bad_command');\n\nchild.on('error', function (err) {\n  console.log('Failed to start child process.');\n});
\n", "properties": [ { "textRaw": "options.detached", "name": "detached", "desc": "

On Windows, this makes it possible for the child to continue running after the\nparent exits. The child will have a new console window (this cannot be\ndisabled).\n\n

\n

On non-Windows, if the detached option is set, the child process will be made\nthe leader of a new process group and session. Note that child processes may\ncontinue running after the parent exits whether they are detached or not. See\nsetsid(2) for more information.\n\n

\n

By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method,\nand the parent's event loop will not include the child in its reference count.\n\n

\n

Example of detaching a long-running process and redirecting its output to a\nfile:\n\n

\n
 var fs = require('fs'),\n     spawn = require('child_process').spawn,\n     out = fs.openSync('./out.log', 'a'),\n     err = fs.openSync('./out.log', 'a');\n\n var child = spawn('prg', [], {\n   detached: true,\n   stdio: [ 'ignore', out, err ]\n });\n\n child.unref();
\n

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.\n\n

\n" }, { "textRaw": "options.stdio", "name": "stdio", "desc": "

As a shorthand, the stdio argument may be one of the following strings:\n\n

\n\n

Otherwise, the 'stdio' option to [child_process.spawn()][] is an array where each\nindex corresponds to a fd in the child. The value is one of the following:\n\n

\n
    \n
  1. '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 ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.stderr, respectively.
  2. \n
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, then this will\ntrigger ChildProcess.on('message'). If the child is an Node.js program, then\nthe presence of an IPC channel will enable process.send() and\nprocess.on('message').
  4. \n
  5. 'ignore' - Do not set this file descriptor in the child. Note that Node.js\nwill always open fd 0 - 2 for the processes it spawns. When any of these is\nignored Node.js will open /dev/null and attach it to the child's fd.
  6. \n
  7. 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. Note that the stream must\nhave an underlying descriptor (file streams do not until the 'open'\nevent has occurred).
  8. \n
  9. Positive integer - The integer value is interpreted as a file descriptor\nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how Stream objects can be shared.
  10. \n
  11. null, 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'.
  12. \n
\n

Example:\n\n

\n
var spawn = require('child_process').spawn;\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 present a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
\n

See also: [child_process.exec()][] and [child_process.fork()][]\n\n

\n" } ] } ], "type": "module", "displayName": "Asynchronous Process Creation" }, { "textRaw": "Synchronous Process Creation", "name": "synchronous_process_creation", "desc": "

These methods are synchronous, meaning they WILL block the event loop,\npausing execution of your code until the spawned process exits.\n\n

\n

Blocking calls like these are mostly useful for simplifying general purpose\nscripting tasks and for simplifying the loading/processing of application\nconfiguration at startup.\n\n

\n", "methods": [ { "textRaw": "child_process.execFileSync(file[, args][, options])", "type": "method", "name": "execFileSync", "signatures": [ { "return": { "textRaw": "return: {Buffer|String} The stdout from the command ", "name": "return", "type": "Buffer|String", "desc": "The stdout from the command" }, "params": [ { "textRaw": "`file` {String} The filename of the program to run ", "name": "file", "type": "String", "desc": "The filename of the program to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`input` {String|Buffer} The value which will be passed as stdin to the spawned process ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "String|Buffer", "desc": "The value which will be passed as stdin to the spawned process" }, { "textRaw": "`stdio` {Array} Child's stdio configuration. (Default: 'pipe') ", "options": [ { "textRaw": "`stderr` by default will be output to the parent process' stderr unless `stdio` is specified ", "name": "stderr", "desc": "by default will be output to the parent process' stderr unless `stdio` is specified" } ], "name": "stdio", "default": "pipe", "type": "Array", "desc": "Child's stdio configuration." }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "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", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String", "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 child process is killed ", "name": "maxBuffer", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer') ", "name": "encoding", "default": "buffer", "type": "String", "desc": "The encoding used for all stdio inputs and outputs." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

execFileSync will not return until the child process has fully closed. When a\ntimeout has been encountered and killSignal is sent, the method won't return\nuntil the process has completely exited. That is to say, if the process handles\nthe SIGTERM signal and doesn't exit, your process will wait until the child\nprocess has exited.\n\n

\n

If the process times out, or has a non-zero exit code, this method will\nthrow. The [Error][] object will contain the entire result from\n[child_process.spawnSync()][]\n\n

\n" }, { "textRaw": "child_process.execSync(command[, options])", "type": "method", "name": "execSync", "signatures": [ { "return": { "textRaw": "return: {Buffer|String} The stdout from the command ", "name": "return", "type": "Buffer|String", "desc": "The stdout from the command" }, "params": [ { "textRaw": "`command` {String} The command to run ", "name": "command", "type": "String", "desc": "The command to run" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`input` {String|Buffer} The value which will be passed as stdin to the spawned process ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "String|Buffer", "desc": "The value which will be passed as stdin to the spawned process" }, { "textRaw": "`stdio` {Array} Child's stdio configuration. (Default: 'pipe') ", "options": [ { "textRaw": "`stderr` by default will be output to the parent process' stderr unless `stdio` is specified ", "name": "stderr", "desc": "by default will be output to the parent process' stderr unless `stdio` is specified" } ], "name": "stdio", "default": "pipe", "type": "Array", "desc": "Child's stdio configuration." }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`shell` {String} Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`.) ", "name": "shell", "type": "String", "desc": "Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`.)" }, { "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", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String", "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 child process is killed ", "name": "maxBuffer", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer') ", "name": "encoding", "default": "buffer", "type": "String", "desc": "The encoding used for all stdio inputs and outputs." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true } ] } ], "desc": "

execSync will not return until the child process has fully closed. When a\ntimeout has been encountered and killSignal is sent, the method won't return\nuntil the process has completely exited. That is to say, if the process handles\nthe SIGTERM signal and doesn't exit, your process will wait until the child\nprocess has exited.\n\n

\n

If the process times out, or has a non-zero exit code, this method will\nthrow. The [Error][] object will contain the entire result from\n[child_process.spawnSync()][]\n\n

\n" }, { "textRaw": "child_process.spawnSync(command[, args][, options])", "type": "method", "name": "spawnSync", "signatures": [ { "return": { "textRaw": "return: {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} The exit code of the child process ", "name": "status", "type": "Number", "desc": "The exit code of the child process" }, { "textRaw": "`signal` {String} The signal used to kill the child process ", "name": "signal", "type": "String", "desc": "The signal used to kill the child process" }, { "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" } ], "name": "return", "type": "Object" }, "params": [ { "textRaw": "`command` {String} The command to run ", "name": "command", "type": "String", "desc": "The command to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`input` {String|Buffer} The value which will be passed as stdin to the spawned process ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "String|Buffer", "desc": "The value which will be passed as stdin to the spawned process" }, { "textRaw": "`stdio` {Array} Child's stdio configuration. ", "name": "stdio", "type": "Array", "desc": "Child's stdio configuration." }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "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", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String", "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 child process is killed ", "name": "maxBuffer", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer') ", "name": "encoding", "default": "buffer", "type": "String", "desc": "The encoding used for all stdio inputs and outputs." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

spawnSync will not return until the child process has fully closed. When a\ntimeout has been encountered and killSignal is sent, the method won't return\nuntil the process has completely exited. That is to say, if the process handles\nthe SIGTERM signal and doesn't exit, your process will wait until the child\nprocess has exited.\n\n

\n" } ], "type": "module", "displayName": "Synchronous Process Creation" } ], "type": "module", "displayName": "Child Process" } ] }