Last active
November 13, 2020 14:36
-
-
Save jadaradix/fd1ef195af87f6890448 to your computer and use it in GitHub Desktop.
Read n lines from file node.js (stream) - inspired by http://stackoverflow.com/questions/6394951/read-nth-line-of-file-in-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
"use strict"; | |
var fs = require("fs"); | |
let getLines = function getLines (filename, lineCount, callback) { | |
let stream = fs.createReadStream(filename, { | |
flags: "r", | |
encoding: "utf-8", | |
fd: null, | |
mode: 438, // 0666 in Octal | |
bufferSize: 64 * 1024 | |
}); | |
let data = ""; | |
let lines = []; | |
stream.on("data", function (moreData) { | |
data += moreData; | |
lines = data.split("\n"); | |
// probably that last line is "corrupt" - halfway read - why > not >= | |
if (lines.length > lineCount + 1) { | |
stream.destroy(); | |
lines = lines.slice(0, lineCount); // junk as above | |
callback(false, lines); | |
} | |
}); | |
stream.on("error", function () { | |
callback("Error"); | |
}); | |
stream.on("end", function () { | |
callback(false, lines); | |
}); | |
}; | |
getLines("home-kitchen.json", 20, function (err, lines) { | |
console.log(err); | |
console.log(lines); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi,
I m new to coding. I need to read first 300 lines from mogodb collection.
here you have mentioned home-kitchen.json as file name, I have already data in a collection. i need to know hw to mention the whole path in place of filename in your code?