child_process.fork(modulePath[, args][, options])
modulePath
String The module to run in the childargs
Array List of string argumentsoptions
Object
cwd
String Current working directory of the child processenv
Object Environment key-value pairsexecPath
String Executable used to create the child processexecArgv
Array List of string arguments passed to the executable (Default: process.execArgv)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)uid
Number Sets the user identity of the process. (See setuid(2).)gid
Number Sets the group identity of the process. (See setgid(2).)
child_process.fork() 能够让你创建一个子进程,并且可以和父进程进行通信。
例子:
main.js
var cp = require('child_process');
var n = cp.fork(__dirname + '/sub.js');
n.on('message', function(m) {
console.log('PARENT got message:', m);
});
n.send({ hello: 'child' });
sub.js
process.on('message', function(m) {
console.log('CHILD got message:', m);
});
process.send({ hello: 'father' });
然后通过node main.js
运行main.js,得到的结果如下
CHILD got message: { hello: 'child' }
PARENT got message: { hello: 'father' }
child_process.send(message[, sendHandle])
message
ObjectsendHandle Handle
object
例子同上