[英]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.