Mr.Smithyyy Mr.Smithyyy - 4 months ago 7
Javascript Question

Search file for keyword, then log the rest of the line

I've browsed other questions on here related to my issue but they are not working in my situation or perhaps I'm using it wrong and need a better explanation.

I'm looking to read a large file, look at the first word to see if it matches the input from the user, then if it does I would like to

console.log
the rest of the line.

File.txt

#one: This is the first line
#two: This is the second line
#three: This is the third line
etc


Node Js

// Take in user input

var msgSplit = userInput.split(" ");

if (msgSplit[0].startsWith("#") {

var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('Custom_Phrases')
});

lineReader.on('line', function(line) {
if(line.indexOf(msgSplit[0]) < 0) {
console.log(line);
}
});
}


This works, kind of, but it returns the line after the one I want. If possible I would like for example if the user types in #one, This is the first line gets logged to the console.

Answer

line.indexOf(msgSplit[0]) < 0 means that your user input is not found. Therefor only lines are shown, which do not match the user input.

Try this:

// Take in user input

var msgSplit = userInput.split(" ");

if (msgSplit[0].startsWith("#") 
{
  var lineReader = require('readline').createInterface({
      input: require('fs').createReadStream('Custom_Phrases')
  });

  lineReader.on('line', function(line) {
    if(line.indexOf(msgSplit[0]) >= 0) 
    {
      console.log(line);
    }
  });
}