user2316602
user2316602

Reputation: 642

Check if two files contain a given string - Function error

I'm making a function that will check if two files contain a given string. If both files DON'T contain the string, it should return undefined :( here is my code:

var fs = require("fs");

function get_uniq(string, file1, file2, callback){
  fs.readFile(file1, 'utf8', function(err, data1) {
    if (err) throw err;

    i = data1.search(string);
    console.log(i);
    if(i == -1){
      fs.readFile(file2, 'utf8', function(err, data2) {
        if (err) throw err;

        j = data2.search(string);
        if(j == -1){
          return 1;
        }
        });

    }
});
  callback();
}
var i = get_uniq("stringThatFilesDoesntContainin", "somefile.txt", "anotherfile.txt", function(){

console.log(i);

});

Any idea what the problem is?

Upvotes: 0

Views: 1197

Answers (1)

user568109
user568109

Reputation: 48013

You should not rely on returning a computed value. In node functions can be executed asynchronously so it can return before the function can finish. To execute when the function completes a callback is given. For e.g.

fs.readFile(file1, 'utf8', function(err, data1) {...});

The function that is passed as the last argument is the callback. It is executed when the file has been read. Trying to return the data will result in undefined value.

In your case the returned values will be undefined for all cases. And callback will be executed in parallel with readFile.

callback must be called from inside readFile for file1 or file2, wherever it can finish logically. To give all the places where callback can be added are :

function get_uniq(string, file1, file2, callback){
  fs.readFile(file1, 'utf8', function(err, data1) {
    if (err)
    {
      throw err;
      callback(err);
    }
    else
    {
      i = data1.search(string);
      console.log(i);
      if(i == -1){
        fs.readFile(file2, 'utf8', function(err, data2) {
          if (err)
          {
            throw err;
            callback(err);
          }
          else
          {
            j = data2.search(string);
            if(j == -1){
              callback(false);
            }
            else
            callback(true);
          }
        });
      }
      else
      callback(false);
    }
  });
}

You can put you return value (true/false) as the argument to callback. Or catch error from inside it. How you will execute the above function will be like :

get_uniq("stringThatFilesDoesntContainin", "somefile.txt", "anotherfile.txt", function(value){
  console.log(value);
}); 

Upvotes: 2

Related Questions