Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the line of a searched text from a file using node.js

I am using fs to read the contents of a file, and then searching for a particular word within that file, if the file contains that word instead of returning boolean or the word, I want the output the line that contains the keyword. How do I output that entire line?

const fs = require("fs");
let file = fs.readFileSync("read.txt", "utf8");
if(file.indexOf("keyword") >= 0) {
    console.log("Line of the keyword");
}

I only want the console.log() to output the line if that line contains the keyword.

like image 967
Romit Avatar asked Dec 25 '18 15:12

Romit


People also ask

How do you return an array of lines from a node js file?

readFileSync method, you will get a Buffer. Convert the Buffer into string Using the toString( ) method. Now use the String. split() method to break the data and the delimiter should be “\n”


1 Answers

Let us first try splitting the string from the file by the new lines. Then the resulting array can be searched for the occurrence of the keyword. If search is successful, print the index of the array which is same as the line number.

const fs = require("fs");
let file = fs.readFileSync("read.txt", "utf8");
let arr = file.split(/\r?\n/);
arr.forEach((line, idx)=> {
    if(line.includes("keyword")){
    console.log((idx+1)+':'+ line);
    }
});
like image 117
Fullstack Guy Avatar answered Sep 20 '22 17:09

Fullstack Guy