Skip to content

Instantly share code, notes, and snippets.

@jadaradix
Last active November 13, 2020 14:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jadaradix/fd1ef195af87f6890448 to your computer and use it in GitHub Desktop.
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
"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);
});
@darshanan24
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment