fbelanger
fbelanger

Reputation: 3568

Learning Nodejs, issues with callbacks and fs.readFile

I am learning Nodejs for school and running into a slight issue with callbacks and fs.readFile(). Unfortunately, I must strictly use native Nodejs modules for this assignment.

I am trying to read a plain text file containing user data asynchronously.

Here what I've got so far:

// node_modules/user/index.js
modules.exports = {
  all: function() {
    fs.readFile(users_file, function(err, data) {
      if (err) throw err;
      var users = {};
      var lines = (""+data).split("\n");
      for (var i = 0; i < lines.length; i++) {
        var col = 0;
        var csv = lines[i].split(",");
        var data = {
          id: csv[++col],
          firstName: csv[++col],
          lastName: csv[++col],
          emailAddress: csv[++col],
          phoneNumber: csv[++col]
        };
        users[""+i] = new User(data);
      }
      console.log(users);
      return users;
    });
  }
}

The output of console.log(users); is correct, however this always returns undefined.

Upvotes: 0

Views: 79

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You seem to be attempting to return some users variable from the callback of the readFile function which doesn't make any sense. You probably want to pass some callback to it which will be invoked when the file is read:

modules.exports = {
    all: function(done) {
        fs.readFile(users_file, function(err, data) {
            if (err) done(err, null);
            ...
            done(null, users);
        });
    }
};

and now when you are calling this all function you are not going to expect any return value from it, but you would rather pass a callback in which you will access the results. Just like that:

xxxx.all(function(err, users) {
    if (err) throw err;
    // TODO: do something with the users parameter here.
});

instead of writing:

var users = xxxx.all();

which will never work because all is an asynchronous function.

Upvotes: 1

Related Questions