Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

node.js - NodeJS ReadLine - Only read the first 2 lines

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...