I'm attempting to extract a single line of a file, given that I know the pathname and the line number, ideally I'd like to do this without reading any more of the file than is necessary.
For the purpose I'm using here, it doesn't matter if this is async or sync.
My current (bad) implementation looks like this:
function get_line(filename, line_no, callback) {
line_no = parseInt(line_no);
var data = fs.readFileSync(filename, 'utf8');
var lines = data.split("\n");
for (var l in lines) {
if (l == line_no - 1) {
callback(null, lines[l].trim());
return;
}
}
throw new Error('File end reached without finding line');
}
I tried to do something with a createReadStream, but the data events never seemed to fire. Can anyone provide a direct solution to this problem, or point me towards some NodeJS filesystem interaction documentation that is a little more example driven than the standard library API docs?