服务模型的变迁:同步、复制进程、多线程和事件驱动。

  1. process.exit(1); // 带错误退出,exit code 1
  2. function clearConsole() {
  3. // This seems to work best on Windows and other systems.
  4. // The intention is to clear the output so you can focus on most recent build.
  5. process.stdout.write('\x1bc');
  6. }

多进程的架构

child_process.fork() 实现进程的复制。

// Master - Worker Pattern
var fork = require('child_process').fork;
var cpus = require('os').cpus();
for (var i = 0; i < cpus.length; i += 1) {
    fork('./worker.js');
}

// Create child_process
spawn();    // create a child process to execute a command
spawnSync();
exec();     // the same as spawn but return a callback to know the process status.
execSync();
execFile(); // create a child process to execute a file
execFileSync();
// 产生一个新的 Node.js进程,同时执行一个特定的模块来产生IPC通道,进而在父进程和子进程之间传输数据
fork(modulePath);

注意:其中 options 中的 maxBuffer 参数表示 stdout / stderr 允许的最大的数据量,如果超过了数据量那么子进程就会被杀死。

进程间通信问题

重点关注 ChildProcess 这个类的设计。

process run based on argv:

process.argv.forEach(function(value, index, args) {  console.log('process.argv[' + index + '] = ' + value);});

The message channel:

process.on('message');
process.send('message');

child.on('message');
child.send('message');
  • process.onMessage() 监听 message
  • worker.send() 发送 message
var childProcess = require('child_process');
var n = childProcess.fork('./son.js');

n.on('message', function(m) {
  console.log('Main Listen: ', m);
});
n.send({ hello: 'son' });