node.js-一次读取子进程标准输出100个字节 [英] node.js - reading child process stdout 100 bytes at a time

查看:129
本文介绍了node.js-一次读取子进程标准输出100个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生一个产生大量数据的孩子(我在这里以 ls -lR /为例)。我想一次异步读取孩子的标准输出100个字节。

I'm spawning a child that produces lots of data (I'm using 'ls -lR /' here as an example). I want to asynchronously read the child's stdout 100 bytes at a time.


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

So I want to do: get100().then(process100).then(get100).then(process100).then(...

由于某种原因,此代码仅循环3次,

For some reason, this code only loops 3 times and I stop getting Readable events. I can't figure out why?

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(); }
)


推荐答案

使用 事件流 ,只要有需要读取的数据(流是异步的),就可以从生成的过程中发出 100个字节的数据:

Using event-stream, you can emit 100 bytes data from the spawned process as long as there is data to read (streams are async):

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();
    });
});

这篇关于node.js-一次读取子进程标准输出100个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆