nodejs(二)child_process模块

1.child_process是Node.js的一个十分重要的模块,通过它可以实现创建多进程,以利用多核计算资源。

child_process模块提供了四个创建子进程的函数,分别是spawnexecexecFilefork其中spawn是最原始的创建子进程的函数,其他三个都是对spawn不同程度的封装

spawn只能运行指定的程序,参数需要在列表中给出,相当于execvp系统函数,而exec可以直接运行复杂的命令。

child_process.spawn(command, [args], [options])

child_process.exec(command, [options], callback)

例如要运行ls -lh /usr,使用spawn需要写成spawn('ls', ['-lh', '/usr']),而exec只需exec('ls -lh /usr')

exec的实现原理是启动了一个系统shell来解析参数,因此可以是非常复杂的命令,包括管道和重定向。

此外,exec还可以直接接受一个回调函数作为参数,回调函数有三个参数,分别是errstdout , stderr,非常方便直接使用,例如:

1 require('child_process').exec( 'ls -lh /usr' , function(err, stdout , stderr ) {
2   console.log( stdout );
3 });

如果使用spawn,则必须写成:

2.fork函数用于直接运行Node.js模块,例如fork('./child.js'),相当于spawn('node', ['./child.js'])

与默认的spawn不同的是,fork会在父进程与子进程直接建立一个IPC管道,用于父子进程之间的通信。例如

1 var n = require('child_process').fork( './child.js'); 
2 n. on ( 'message', function(m) { 
3   console. log ( 'PARENT got message:', m);
4 });
5 n.send({ hello: 'world' });

child.js的内容

1 process. on ( 'message', function(m) { 
2   console. log ( 'CHILD got message:', m);
3 });
4 process.send({ foo: 'bar' });

结果:

1 PARENT got message: { foo: 'bar' }
2 CHILD got message: { hello: 'world' }

3.fork函数有一个问题,就是它只能运行JavaScript代码,如果你喜欢用CoffeeScript(或者其他任何编译到js的语言),是无法通过fork调用的。

一个简单的方法是把代码编译到JavaScript再运行,但是很不方便,有没有什么办法呢?答案是可以的,

child_process.spawn(command, [args], [options])

通过把options参数的stdio设为['ipc']

即可在父子进程之间建立IPC管道。例如子进程使用CoffeeScript:

1 child_process = require ('child_process');
2  options ={stdio: ['ipc'] };
3 child = child_process.spawn('coffee', ['./child.coffee'], options);

其中只要把spawn的第一个参数设置为运行对应脚本的解释器,即可运行,例如使用Continuation.js

只需child = child_process.spawn('continuation', ['./child.coffee'], options)

原文地址:https://www.cnblogs.com/yuyutianxia/p/3271755.html