Search for a keyword in multiple files and return me the result with previous and following line

204 Views Asked by At

I'm using Node JS, I want to search for a keyword in multiple .txt files, and then that return me the previous line and the following one.

Im expecting something like this:

Cars
Scooters
Skates
Airplanes
Ships
Trucks
Bikes

Then I search for the word using some nodejs package, in this example is ship. So the package return to me the line that is upper and down. For example something like this:

{"result":"
Airplanes
Ships
Trucks
"}
1

There are 1 best solutions below

2
Muhammed Sidan On BEST ANSWER

You can use the built-in fs module to read the contents of the text files

https://www.w3schools.com/nodejs/nodejs_filesystem.asp

const fs = require('fs');

function searchKeywordInFiles(keyword, files) {
  const results = [];

  files.forEach(file => {
    const data = fs.readFileSync(file, 'utf8');
    const lines = data.split('\n');

    for (let i = 0; i < lines.length; i++) {
      if (lines[i].includes(keyword)) {
        const previousLine = lines[i - 1] || '';
        const nextLine = lines[i + 1] || '';

        results.push({
          result: `${previousLine}\n${lines[i]}\n${nextLine}`
        });
      }
    }
  });

  return results;
}

// Example usage
const keyword = 'ship';
const files = ['file1.txt', 'file2.txt', 'file3.txt']; // Replace with your actual file names

const searchResults = searchKeywordInFiles(keyword, files);
console.log(searchResults);

In this example, the searchKeywordInFiles function takes a keyword and an array of files as parameters. It reads each file using fs.readFileSync, splits the content into lines, and iterates over each line to check if it contains the keyword.

If a line contains the keyword, it retrieves the previous line (if available) and the next line (if available) and adds them to the results array. Finally, it returns the array of search results.