node.js - 一次读取子进程stdout 100个字节

时间:2016-01-24 02:39:39

标签: node.js stream child-process

我正在产生一个产生大量数据的孩子(我在这里使用'ls -lR /'作为例子)。我想一次异步读取孩子的stdout 100字节。

  

所以我想这样做:get100()。然后(process100).then(get100).then(process100).then(...

出于某种原因,此代码仅循环3次,我停止获取可读事件。我想不通为什么?

var Promise = require('bluebird');
var spawn   = require("child_process").spawn;

var exec = spawn( "ls", [ "-lR", "/"] );  

var get100 = function () {
     return new Promise(function(resolve, reject) {
       var tryTransfer = function() {
          var block = exec.stdout.read(100);
          if (block) {
            console.log("Got 100 Bytes");
            exec.stdout.removeAllListeners('readable');  
            resolve();
          } else console.log("Read Failed - not enough bytes?");
        };
        exec.stdout.on('readable', tryTransfer);
    });
};

var forEver = Promise.method(function(action) {
    return action().then(forEver.bind(null, action));
});

forEver(
    function() { return get100(); }
)

1 个答案:

答案 0 :(得分:2)

使用event-stream,只要有要读取的数据(流是异步的),就可以从生成的进程发出 100字节数据:

var es = require('event-stream');
var spawn = require("child_process").spawn;

var exec = spawn("ls", ["-lR", "/"]);

var stream = es.readable(function (count, next) {
    // read 100 bytes
    while (block = exec.stdout.read(100)) {
        // if you have tons of data, it's not a good idea to log here
        // console.log("Got 100 Bytes");
        // emit the block
        this.emit('data', block.toString()); // block is a buffer (bytes array), you may need toString() or not
    }

    // no more data left to read
    this.emit('end');
    next();
}).on('data', function(data) {
    // data is the 100 bytes block, do what you want here

    // the stream is pausable and resumable at will
    stream.pause();
    doStuff(data, function() {
        stream.resume();
    });
});