{ "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
It is possible to stream data through a child's stdin
, stdout
, and\nstderr
in a fully non-blocking way.\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
ChildProcess
is an EventEmitter
.\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
The ChildProcess class is not intended to be used directly. Use the\nspawn()
or fork()
methods to create a Child Process instance.\n\n
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
See waitpid(2)
.\n\n
A Writable Stream
that represents the child process's stdin
.\nClosing this stream via end()
often causes the child process to terminate.\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
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
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
\nExample:\n\n
\nvar 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
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');
\nNote 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
See kill(2)
\n\n
Send a message (and, optionally, a handle object) to a child process.\n\n
\nSee child_process.fork()
for details.\n\n
Launches a new process with the given command
, with command line arguments in args
.\nIf omitted, args
defaults to an empty Array.\n\n
The third argument is used to specify additional options, which defaults to:\n\n
\n{ cwd: undefined,\n env: process.env\n}
\ncwd
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
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the exit code:\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});
\nExample: A very elaborate way to run 'ps ax | grep ssh'\n\n
\nvar 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});
\nExample of checking for failed exec:\n\n
\nvar 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});
\nNote 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
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
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
See also: child_process.exec()
and child_process.fork()
\n\n
Runs a command in a shell and buffers the output.\n\n
\nvar 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});
\nThe 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
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 }
\nIf 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
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
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
For example:\n\n
\nvar 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' });
\nAnd then the child script, 'sub.js'
might look like this:\n\n
process.on('message', function(m) {\n console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\nIn 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
By default the spawned Node process will have the stdin, stdout, stderr\nassociated with the parent's.\n\n
\nThese 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
\nThe 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
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});
\nHere is an example of receiving the server handle and sharing it between\nprocesses:\n\n
\nprocess.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"
}
]
}