NodeJS ReadLine - Only read the first 2 lines

Viewed 16510

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?

2 Answers

for those of you who can't make the linereader stop, do this:

lineReader.close()
lineReader.removeAllListeners()
Related