Solution : Streaming the read
Most efficient for all scenarios.
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(__dirname+'/sample.txt'),
});
var lineCounter = 0; var wantedLines = [];
lineReader.on('line', function (line) {
lineCounter++;
wantedLines.push(line);
if(lineCounter==2){lineReader.close();}
});
lineReader.on('close', function() {
console.log(wantedLines);
process.exit(0);
});
Solution : Full-Read, then split
(Not efficient for large files) Simple read & new-line split working example :
const fs = require('fs');
fs.readFile(__dirname+'/sample.txt', "utf8", (err, data) => {
if(err){console.log(err);}else{
data = data.split("
"); // split the document into lines
data.length = 2; // set the total number of lines to 2
console.log(data); //Array containing the 2 lines
}
});
the sample.txt file :
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
Running this script will output :
[ 'This is line 1', 'This is line 2' ]
REGARDING QUESTION's EXAMPLE CODE : (SUGGESTION)
If the file to be read is going to be the same on every request. You should load it (store it) into a global variable (if not too big) or a new file (would require to be read again in order to be served) at server startup, for example in your listen callback. You will avoid repeating the same task (reading the file into a string, spliting every line, and keeping the first 2) every time someone performs a request on the given route.
Hope it helped.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…