【问题标题】:Whole file read when passing a file read stream to readline.createInterface in Node.js将文件读取流传递给 Node.js 中的 readline.createInterface 时读取整个文件
【发布时间】:2020-03-12 19:24:26
【问题描述】:

我正在一个大文件上创建一个文件读取流并将其传递给readline.createInterface。目标是在此之后使用for await ... of 从文件中获取行而不将其全部读入内存。

但是,即使我什么都没读,整个流似乎都被处理了。我知道发生这种情况是因为我尝试监听事件(并且它们已被发出),而且如果我使用非常大的文件,我的脚本需要一段时间才能完成。

有没有办法避免这种行为?我希望按需使用流。

如果我不使用readline,而是从流中读取块并自己搜索行,我可以成功实现此行为,但如果可能的话,我想避免这种情况。

MWE:

var readline = require('readline');
var fs = require('fs');
var file = 'really_big_file.txt'; // 2GB is what I used

readline.createInterface({input: fs.createReadStream(file)});

// this takes a while to finish because the file is being read,
//  even if I'm not doing anything with the stream

【问题讨论】:

    标签: node.js fs readline node-streams


    【解决方案1】:

    来自readline的官方documentation包:

    const fs = require('fs');
    const readline = require('readline');
    
    async function processLineByLine() {
      const fileStream = fs.createReadStream('/tmp/input.txt');
      // If you want to start consuming the stream after some point
      // in time then try adding the open even to the readstream
      // and explictly pause it
      fileStream.on('open', () => {
        fileStream.pause();
    
    
        // Then resume the stream when you want to start the data flow
        setInterval(() => {
          fileStream.resume();
        }, 1000)
      });
    
      const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
      });
      // Note: we use the crlfDelay option to recognize all instances of CR LF
      // ('\r\n') in input.txt as a single line break.
    
      for await (const line of rl) {
        // Each line in input.txt will be successively available here as `line`.
        console.log(`Line from file: ${line}`);
      }
    
      console.log("reading finished");
    }
    
    processLineByLine();
    

    尝试将接口存储在一个变量中,并进一步使用它进行迭代。这里发生的是 readline 开始并一直持续到因为没有任何东西要求它等待

    延伸阅读:https://wanago.io/2019/03/04/node-js-typescript-4-paused-and-flowing-modes-of-a-readable-stream/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-09
      • 2012-11-04
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多