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

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

Stack Overflow用户
提问于 2016-09-09 23:10:05
回答 3查看 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

回答 3

Stack Overflow用户

发布于 2018-07-24 00:49:46

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

代码语言:javascript
复制
const line_counter = ((i = 0) => () => ++i)();

在创建回调函数时,我们只需将第二个参数默认给line_counter函数,我们就可以当作在发生line事件时同时传递行号

代码语言:javascript
复制
rl.on("line", (line, lineno = line_counter()) => {
  console.log(lineno); //1...2...3...10...100...etc
});
票数 18
EN

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 归档