NodeJS ReadLine - 仅读取前两行

use*_*645 2 node.js

我试图在NodeJS中创建一个脚本,它返回文本文件的前两行.

我目前正在使用此代码:

// 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}`)
})
Run Code Online (Sandbox Code Playgroud)

所以这会返回所有行,但我只想让它返回前2行.

我怎样才能做到这一点?

EMX*_*EMX 14

解决方案:流式读取

对所有场景最有效.

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);
});
Run Code Online (Sandbox Code Playgroud)

解决方案:完全读取,然后拆分

(对于大文件效率不高)简单的读取和换行分组工作示例:

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
  }
});
Run Code Online (Sandbox Code Playgroud)

sample.txt的文件:

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
Run Code Online (Sandbox Code Playgroud)

运行此脚本将输出:

[ 'This is line 1', 'This is line 2' ]
Run Code Online (Sandbox Code Playgroud)

关于问题的示例代码:(建议)

如果要读取的文件在每个请求中都是相同的.您应该在服务器启动时将它(存储它)加载到全局变量(如果不是太大)或新文件(需要再次读取以便提供服务),例如在listen回调中.每当有人在给定路线上执行请求时,您将避免重复相同的任务(将文件读入字符串,拆分每一行,并保留前两个).

希望它有所帮助.


Oz *_*bat 10

对于那些无法让线路阅读器停止的人,请执行以下操作:

lineReader.close()
lineReader.removeAllListeners()
Run Code Online (Sandbox Code Playgroud)