繁体   English   中英

Node.js Readline,获取当前行号

[英]Node.js Readline, get the current line number

我有以下实现,除了这一行,一切正常:

lineNumber: line.lineNumber

此行返回未定义,我在下面添加了完整的代码片段,我的问题是: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));
  }
 });
};

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

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

当我们创建回调函数时,我们只是将第二个参数默认为line_counter函数,我们可以表现得好像行号line事件发生时被传递。

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

简单地说,将变量增量与 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)
}

如果您使用节点 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 
          });
     }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM