使用换行符读取节点子进程(spawn)stdout

时间:2015-03-24 15:38:11

标签: node.js stdout line-breaks spawn

我正在尝试使用

在node.js中运行子进程
function runProcess (args) {
  args = args || [];
  var proc = spawn('node', [path.join(__dirname, '..', 'bin', 'library.js')].concat(args), {cwd: __dirname});
  proc.stdout.setEncoding('utf8');
  return proc;
}

我有一个测试,我使用上面的函数:

describe('test', function () {
  it('should list installed generators', function (done) {
    var process = runProcess();
    var data = '';
    process.stdout.on('data', function(data) {
        var str = data.toString(), lines = str.split(/(\r?\n)/g);
        for (var i=0; i<lines.length; i++) {
            console.log("chucnk ---------> " + lines[i]); // only prints one line
       }
    });
    process.on('close', function (code) {
      code.should.equal(0);
      data.should.match(/\[process\] ├── bad/);
      data.should.match(/\[process\] └── test/);
      done();
    });
  });

该过程使用chalk和一个名为log.js的文件来显示控制台输出:

var chalk = require('chalk');

module.exports = function(){
  'use strict';
  var sig = '['+chalk.green('process')+']';
  var args = Array.prototype.slice.call(arguments);
  args.unshift(sig);
  console.log.apply(console, args); // Invoked 3 times!
  return this;
};

如果我手动运行该过程,我可以看到预期的输出:

[process] Installed generators
[process] ├── bad
[process] └── test

当我在单元测试中运行时,第2行和第3行缺失

chucnk ---------> [process] Installed generators
chucnk ---------> 
chucnk ---------> 

我在NodeJS spawn stdout string format尝试了提议而没有运气。

你知道为什么我不能在第一个之后阅读这些内容吗?

0 个答案:

没有答案
相关问题