Home >Web Front-end >JS Tutorial >How Can I Read a File Line by Line in Node.js?

How Can I Read a File Line by Line in Node.js?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 22:11:13518browse

How Can I Read a File Line by Line in Node.js?

Read a File One Line at a Time in Node.js

Node.js provides efficient mechanisms for processing large files one line at a time. This capability is essential for memory-intensive operations or when dealing with files that exceed server memory.

To read a file line by line in Node.js, you can utilize the following approaches:

Using the readline Core Module (Node.js v0.12 )

Node.js offers a readline core module for seamless file line iteration. Consider the following code:

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

Using the 'readline' Package

For Node.js versions prior to v0.12, the 'readline' package provides an alternative solution:

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

lineReader.on('line', function (line) {
  console.log('Line from file:', line);
});

lineReader.on('close', function () {
    console.log('all done, son');
});

In both approaches, the last line is read correctly even without a trailing newline character.

Additional Considerations

  • Ensure that the file path provided in 'createReadStream()' is accurate.
  • Handle errors appropriately using try-catch blocks or event listeners.
  • The readline module's 'close' event is emitted when the end of the file is reached or an error occurs.

The above is the detailed content of How Can I Read a File Line by Line in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn