Read a file one line at a time in node.js?

前端 未结 29 1087
深忆病人
深忆病人 2020-11-22 04:33

I am trying to read a large file one line at a time. I found a question on Quora that dealt with the subject but I\'m missing some connections to make the whole thing fit to

29条回答
  •  孤独总比滥情好
    2020-11-22 04:53

    Update in 2019

    An awesome example is already posted on official Nodejs documentation. here

    This requires the latest Nodejs is installed on your machine. >11.4

    const fs = require('fs');
    const readline = require('readline');
    
    async function processLineByLine() {
      const fileStream = fs.createReadStream('input.txt');
    
      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}`);
      }
    }
    
    processLineByLine();
    

提交回复
热议问题