Im trying to make a Script in NodeJS, which returns the first 2 lines of a text file.
Im currently using this code:
// content of index.js
const fs = require('fs')
const readline = require('readline');
const http = require('http')
const port = 8080
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
const requestHandler = (request, response) => {
console.log(request.url)
if (request.url == "/newlines") {
filename = "allnames.txt"
readline.createInterface({
input: fs.createReadStream(filename),
output: process.stdout
})
response.end('Hello Node.js Server!')
}
else {
response.end('Go away!')
}
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
So this returns all lines, but I only want to let it return the first 2.
How can I do that?
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);
});
(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("\n"); // 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' ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With