使用缓冲区和流在多个文本文件中搜索字符串,并在 nodejs 中查找行号

using buffer& streams to search for string in multiple text file & also to find line number in nodejs

请帮助我在多个文件中搜索字符串,我需要使用 node.js 中的缓冲区和流概念打印带有文件名的特定字符串的行号。

例如:

有5个文本文件,第3个文件的第10行和第15行有“hello”字符串。第 5 个文件的第 50 行中的相同 hello 字符串。现在我需要打印文件名 3 的行号和该搜索字符串的行号 "hello" 与第 5 个文件相同。

帮我用node.js

中的缓冲区概念写这个程序

const readline = require("readline");
const fs = require("fs");

// Start methods implementation
const beginSearch = (readStream, filePath, queries) => {
  let lineCount = 0;
  let matches = new Map();
  queries.forEach(query => matches.set(query, []));

  return new Promise((resolve, reject) => {
    readStream.on("line", line => {
      lineCount++;
      for (query of matches.keys()) {
        if (searchForTerm(line, query))
          matches.set(query, [...matches.get(query), lineCount]);
      }
    });

    readStream.on("close", () => resolve({
      filePath,
      matches
    }));
  });
};
const searchForTerm = (line, query) => line.match(query);

const createLineInterfaces = filePaths =>
  filePaths.map(filePath => {
    const readStream = readline.createInterface({
      input: fs.createReadStream(filePath),
      crlfDelay: Infinity
    });
    return {
      filePath,
      readStream
    };
  });
// End methods implementation


// Start main function

const filesToSearch = ["sample.txt", "sample2.txt"];
const queriesToSeatch = ["hello"];
let searchProms = createLineInterfaces(filesToSearch).map(
  ({
    readStream,
    filePath
  }) =>
  beginSearch(readStream, filePath, queriesToSeatch)
);

Promise.all(searchProms).then(searchResults =>
  searchResults.forEach(result => console.log(result))
);
// End main function

稍微解释一下

我正在使用 readline 模块将每个文件拆分成行。 请记住,整个实现都是使用流。然后我将一个侦听器附加到 line 事件,并在每一行中搜索特定查询。搜索方法是一个简单的正则表达式。如果需要,您可以使用模糊搜索方法。然后将匹配的行保存在 Map 中,其中键是查询,值是查询找到的 lineNumbers 的数组。

我假设您熟悉 stream 概念并且了解 ES6 内容。