node.js – 一次读取100个字节的subprocess标准输出

我产生了一个产生大量数据的孩子(我在这里使用'ls -lR /'作为例子)。 我想同步读取孩子的标准输出100个字节。

所以我想要做的:get100()。然后(process100)。然后(get100)。然后(process100)。然后(…

出于某种原因,这段代码只循环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(); } ) 

使用event-stream ,只要有数据要读取(stream是asynchronous的),就可以从产生的进程中发出 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(); }); });