【nodejs --学习01】: node之child_process

来源:互联网 发布:php上传图片插件 编辑:程序博客网 时间:2024/06/05 02:48

child_process.fork(modulePath[, args][, options])

  • modulePath String The module to run in the child
  • args Array List of string arguments
  • options Object
    • cwd String Current working directory of the child process
    • env Object Environment key-value pairs
    • execPath String Executable used to create the child process
    • execArgv 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 Object
  • sendHandle Handle object

例子同上

原创粉丝点击