JavaScript Read File Line by Line: A Comprehensive Guide
To read a file line by line in JavaScript, you can use the 'readline' module from the Node.js standard library. Here's an example:
const readline = require('readline');
const fs = require('fs');
const fileStream = fs.createReadStream('example.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
rl.on('line', (line) => {
console.log('Line from file: ' + line);
});
rl.on('close', () => {
console.log('End of file');
});
In this example, we first require the 'readline' and 'fs' modules. We then create a readable stream from the file using 'fs.createReadStream()'. Next, we create an instance of 'readline.Interface' using 'readline.createInterface()', passing in the file stream as the input.
We listen for the 'line' event on the 'readline.Interface' instance, which is emitted each time a new line is read from the file. Within the event listener, we can process each line as needed.
Finally, we listen for the 'close' event, which is emitted when the end of the file is reached.
Make sure to replace 'example.txt' with the path to your file.
原文地址: https://www.cveoy.top/t/topic/pj9Z 著作权归作者所有。请勿转载和采集!