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

Node 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.\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", "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\nspawn() or fork() methods to create a Child Process instance.\n\n

\n", "events": [ { "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

See waitpid(2).\n\n

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

A Writable Stream that represents the child process's stdin.\nClosing this stream via end() often causes the child process to terminate.\n\n

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

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

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

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

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

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

\n

If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

\n" }, { "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" } ], "methods": [ { "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('exit', 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

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

\n

See kill(2)\n\n

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

Send a message (and, optionally, a handle object) to a child process.\n\n

\n

See child_process.fork() for details.\n\n

\n" } ] } ], "methods": [ { "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": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" } ], "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 args.\nIf omitted, args defaults to an empty Array.\n\n

\n

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

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

cwd allows you to specify the working directory from which the process is spawned.\nUse env to specify environment variables that will be visible to the new process.\n\n

\n

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

\n
var util  = require('util'),\n    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('exit', 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 util  = require('util'),\n    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('exit', 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('exit', 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.stderr.setEncoding('utf8');\nchild.stderr.on('data', function (data) {\n  if (/^execvp\\(\\)/.test(data)) {\n    console.log('Failed to start child process.');\n  }\n});
\n

Note that if spawn receives an empty options object, it will result in\nspawning the process with an empty environment rather than using\nprocess.env. This due to backwards compatibility issues with a deprecated\nAPI.\n\n

\n

There is a deprecated option called customFds which allows one to specify\nspecific file descriptors for the stdio of the child process. This API was\nnot portable to all platforms and therefore removed.\nWith customFds it was possible to hook up the new process' [stdin, stdout,\nstderr] to existing streams; -1 meant that a new stream should be created.\nUse at your own risk.\n\n

\n

There are several internal options. In particular stdinStream,\nstdoutStream, stderrStream. They are for INTERNAL USE ONLY. As with all\nundocumented APIs in Node, they should not be used.\n\n

\n

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

\n" }, { "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": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" }, { "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} (Default: 200*1024) ", "name": "maxBuffer", "default": "200*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "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 util = require('util'),\n    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 err.code\nwill be the exit code of the child process, and err.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 allowed on stdout or stderr - if this value is exceeded then\nthe child process is killed.\n\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" }, { "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": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" }, { "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} (Default: 200*1024) ", "name": "maxBuffer", "default": "200*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "name": "options", "type": "Object" }, { "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": "file" }, { "name": "args" }, { "name": "options" }, { "name": "callback" } ] } ], "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": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" }, { "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" } ], "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 spawn() functionality for spawning Node\nprocesses. In addition to having all the methods in a normal ChildProcess\ninstance, the returned object has a communication channel built-in. The\nchannel is written to with child.send(message, [sendHandle]) and messages\nare received by a '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

By default the spawned Node process will have the stdin, stdout, stderr\nassociated with the parent's.\n\n

\n

These child Nodes are still whole new instances of V8. Assume at least 30ms\nstartup and 10mb memory for each new Node. That is, you cannot create many\nthousands of them.\n\n

\n

The sendHandle option to child.send() is for sending a handle object to\nanother process. Child will receive the handle as as second argument to the\nmessage event. Here is an example of sending a handle:\n\n

\n
var server = require('net').createServer();\nvar child = require('child_process').fork(__dirname + '/child.js');\n// Open up the server object and send the handle.\nserver.listen(1337, function() {\n  child.send({ server: true }, server._handle);\n});
\n

Here is an example of receiving the server handle and sharing it between\nprocesses:\n\n

\n
process.on('message', function(m, serverHandle) {\n  if (serverHandle) {\n    var server = require('net').createServer();\n    server.listen(serverHandle);\n  }\n});
\n" } ], "type": "module", "displayName": "Child Process" } ] }