0

I am passing string from client side and if that string is part of that file content i want to print that line , is it doable using fs and nodejs ?

searvice.js

var fs = require('fs');
var path = require('path');
var async = require('async');
var searchStr;

function readFile(str){
    searchStr = str;
//  var url = './logs/St/server1.log';
    fs.readFile('./logs/St/server1.log', 'utf8', function (err,data) {
      if (err) {
        return console.log(err);
      }
      console.log('Server Data',data);
      inspectFile(data);
    });
}


function inspectFile(data) {
    if (data.indexOf(searchStr) != -1) {
        // do something
        console.log('print the matching data');
    }
}

exports.readFile = readFile;
2
  • Do you want to print all the lines that matched or just the first one? Commented Feb 24, 2017 at 20:09
  • Yes i want to print all the lines that are matched Commented Feb 24, 2017 at 20:11

1 Answer 1

1

You have first to split data by new lines. Try this:

function inspectFile(data) {
    var lines = data.split('\n');              // get the lines
    lines.forEach(function(line) {             // for each line in lines
        if(line.indexOf(searchStr) != -1) {    // if the line contain the searchStr
            console.log(line);                 // then log it
        }
    });
}

Note: instead of making searchStr global, you could just pass it as parametter to inspectFile.

Sign up to request clarification or add additional context in comments.

4 Comments

How you see this approach in case of async it will work ?
@hussain you're calling it from inside the callback of the asynch function so I think it'll work.
@hussain Did you try it?
Yeah it worked what i was trying to achieve. Thanks alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.