我有下面的实现,除了这一行之外,所有的东西都可以工作:
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));
}
});
};
发布于 2020-05-12 02:05:58
简单地说,将变量增量与foo(++i,data)一起使用,它将始终将新行的编号传递给函数。
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)
}
发布于 2016-09-09 23:21:33
如果使用的是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
});
}
});
https://stackoverflow.com/questions/39414679
复制相似问题