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
"}
You can use the built-in
fsmodule to read the contents of the text fileshttps://www.w3schools.com/nodejs/nodejs_filesystem.asp
In this example, the
searchKeywordInFilesfunction takes a keyword and an array of files as parameters. It reads each file usingfs.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.