Node.js Readline,获取当前行号

时间:2016-09-09 15:10:05

标签: javascript node.js

我有以下实现,其中一切正常但是这一行:

lineNumber: line.lineNumber

此行返回undefined,我在下面添加完整的代码片段,我的问题是:Readline是否提供了以某种方式获取行号的标准方法?或者我必须实施我的计数器来跟踪行号,这很简单,但我不想要它是否有标准的方法呢?

/**
* Search for occurrences of the specified pattern in the received list of files.
* @param filesToSearch - the list of files to search for the pattern
* @returns {Promise} - resolves with the information about the encountered matches for the pattern specified.
*/
const findPattern = (filesToSearch) => {
console.log(filesToSearch);
return new Promise((resolve, reject) => {
 var results = [ ];
 // iterate over the files
 for(let theFile of filesToSearch){
  let dataStream = fs.createReadStream(theFile);
  let lineReader = readLine.createInterface({
    input: dataStream
  });

  let count = 0; // this would do the trick but I'd rather use standard approach if there's one
  // iterates over each line of the current file
  lineReader.on('line',(line) => {
    count++;
    if(line.indexOf(searchPattern) > 0) {
      let currLine = line.toString();
      currLine = currLine.replace(/{/g, '');//cleanup { from string if present
      results.push({
        fileName: theFile,
        value: currLine,
        lineNumber: line.lineNumber //HERE: this results undefined
        //lineNumber: count // this does the trick but I'd rather use standard approach.
      });
    }
  });

   // resolve the promise once the file scan is finished.
   lineReader.on('close', () => resolve(results));
  }
 });
};

3 个答案:

答案 0 :(得分:3)

不幸的是,没有办法使用readline节点模块来查找行号,但是,使用ES6,在一行代码中滚动自己的计数器并不困难。

const line_counter = ((i = 0) => () => ++i)();

创建回调函数时,我们只需将第二个参数默认为line_counter函数,我们就可以像 line line number 发生line事件时都将被传递。

rl.on("line", (line, lineno = line_counter()) => {
  console.log(lineno); //1...2...3...10...100...etc
});

答案 1 :(得分:2)

简单地,将变量增量与foo(data,++ i)一起使用,它将始终将新行的编号传递给函数。

let i = 0
const stream = fs.createReadStream(yourFileName)
stream.pipe().on("data", (data) => foo(data, ++i))

const foo = (data, line) => {
  consle.log("Data: ", data)
  consle.log("Line number:", line)
}

答案 2 :(得分:0)

如果您使用node linereader

,则需要包含lineno参数
lineReader.on('line', function (lineno, line) {
    if(line.indexOf(searchPattern) > 0) {
          let currLine = line.toString();
          currLine = currLine.replace(/{/g, '');//cleanup { from string if present
          results.push({
            fileName: theFile,
            value: currLine,
            lineNumber: lineno 
          });
     }
});