1

我是 node.js 的新手,不了解有关流的文档。希望能得到一些提示。

我正在读取一个非常大的文件行,然后对于每一行我都调用一个异步网络 api。

显然,本地文件的读取速度比异步调用完成的速度要快得多:

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream(program.input)
});

lineReader.on('line', function (line) {
    client.execute(query, [line], function(err, result) {
        // needs to pressure the line reader here
        var myJSON = JSON.stringify(result);
        console.log("line=%s json=%s",myJSON);
    });
});

在“执行”方法中添加背压的方法是什么?

4

1 回答 1

2

解决方案是将异步行为包装在流写入器中,并从写入器中限制异步读取器:

val count = 0;
var writable = new stream.Writable({
    write: function (line, encoding, next) {
        count++;
        if (count < concurrent) {
            next();
        }

        asyncFunctionToCall(...) {
            // completion callback
            // reduce the count and release back pressure
            count--;
            next();
            ...
      }
});

var stream = fs.createReadStream(program.input, {encoding: 'utf8'});
stream = byline.createStream(stream);
stream.pipe(writable);
于 2018-05-05T16:36:48.957 回答