Last active
July 7, 2022 13:25
-
-
Save mholtzhausen/25bcdb0905ff0d6b140d3e32ad189d33 to your computer and use it in GitHub Desktop.
Read a number of lines from a file with Nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const events = require('events') | |
const readline = require('readline') | |
const readLinesFromFile = async function(file, start, count) { | |
let end = start + count | |
let lines = [] | |
try{ | |
let rl = readline.createInterface({ | |
input: fs.createReadStream(file), | |
crlfDelay: Infinity | |
}) | |
let lineCount=0 | |
rl.on('line', line => { | |
if(lineCount>end+1){ | |
return rl.close() | |
} | |
if(lineCount>=start && lineCount<end){ | |
lines.push(line) | |
} | |
lineCount++ | |
}) | |
await events.once(rl,'close'); | |
return lines | |
}catch(err){ | |
console.log(err) | |
} | |
} | |
module.exports = readLinesFromFile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment