node js fs read text file line by line code example
Example 1: node.js read text file line by line
const readline = require('readline');
const readInterface = readline.createInterface({
input: fs.createReadStream('name.txt'),
output: process.stdout,
console: false
});
for await (const line of readInterface) {
console.log(line);
}
readInterface.on('line', function(line) {
console.log(line);
});
Example 2: node read file line
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
});
for await (const line of rl) {
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
Example 3: File line by line reader Node js
lineReader.open('file.txt', function(reader) {
if (reader.hasNextLine()) {
reader.nextLine(function(line) {
console.log(line);
});
}
});