Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Last active July 7, 2022 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mholtzhausen/25bcdb0905ff0d6b140d3e32ad189d33 to your computer and use it in GitHub Desktop.
Save mholtzhausen/25bcdb0905ff0d6b140d3e32ad189d33 to your computer and use it in GitHub Desktop.
Read a number of lines from a file with Nodejs
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