首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js Readline,获取当前行号

Node.js Readline,获取当前行号
EN

Stack Overflow用户
提问于 2016-09-09 23:10:05
回答 2查看 7.8K关注 0票数 7

我有下面的实现,除了这一行之外,所有的东西都可以工作:

代码语言:javascript
复制
lineNumber: line.lineNumber

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

代码语言:javascript
复制
/**
* 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));
  }
 });
};
EN

回答 2

Stack Overflow用户

发布于 2020-05-12 02:05:58

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-09-09 23:21:33

如果使用的是node linereader,则需要包含lineno参数

代码语言:javascript
复制
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 
          });
     }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39414679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档