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
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!