Node.js Readline,获取当前行号

10

我有以下实现,其中一切都正常工作,但这行代码存在问题:

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个回答

23

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

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

当我们创建回调函数时,我们只需将第二个参数默认为line_counter函数,这样在line事件发生时,我们可以像两个参数都被传递一样处理line行号

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

3

简单地说,使用变量递增和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)
}

添加一些代码解释会更好。 - keikai
虽然这段代码可能为问题提供了解决方案,但最好添加上下文来解释它的原理和如何工作。这有助于未来的用户学习并将这些知识应用到自己的代码中。当代码被解释清楚时,你还可能会得到其他用户的积极反馈和点赞。 - borchvm
在代码中添加注释,以便帮助未来的其他人。 :D - Marcio dos A. Junior

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 
          });
     }
});

1
嗨,这看起来不错,谢谢。然而我正在使用标准的Node.js方法:https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line,我不想也不会添加新的依赖项只是为了得到行号,我宁愿使用已经工作的自定义计数器,我只是期望标准库中会有像你刚提到的库一样的内置功能。 - groo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接