1 初探 child_process
1.1 fork
- child_process.fork(modulePath, [args], [options])
-
modulePath{String} 子进程中运行的模块args{Array} 字符串参数列表options{Object}cwd{String} 子进程的当前工作目录env{Object} 环境变量键值对encoding{String} 编码(缺省为 'utf8')execPath{String} 创建子进程的可执行文件
- 返回:ChildProcess 对象
app.js
/**
* Created by Administrator on 2015/5/2.
*/
var express = require('express');
var childProcess = require('child_process');
var app = express();
app.get('/', function (req, res) {
var parentProcess = childProcess.fork('./childProcess.js');
parentProcess.send({message: 'hello I am father'});
parentProcess.on('message', function (message) {
console.log('parent receive message:' + message);
});
//setTimeout(function(){
// parentProcess.send({message: 'hello I am father'});
//},5000);
res.send('hello world');
});
app.listen('3000', function () {
console.log('server on port 3000');
});
childProcess.js
/**
* Created by Administrator on 2015/5/2.
*/
//parent process 每一次发消息都会触发
process.on('message', function (message) {
console.log('child receive message:' + message.message);
for (var i = 0; i < 10; i++) {
process.send('hi Iam child');
}
process.send('hi Iam child,end');
setTimeout(function(){
process.send('hi Iam child,again');
},5000);
});