Callback- not defined

I have a file, (lets call it "file1") where I insert a key value and fetch it as well; so here I have my implementation for file1:

var rdb;

module.exports = function(_app) {    
    rdb = redis.createClient();
    return module.exports;
}


module.exports.parse = function (name, callback) {
        rdb.set(name, 'myValue', function(err, data) {
            console.log("SET:", err, data);
        });
        rdb.get(name, function(err, value) {
            callback(err, value);
        });
}

But when I'm calling my parse function in another file it says parse undefined:

var f1;
module.exports = function(_app) {
    app = _app;    
    f1 = require('./file1.js')(_app);
};



f1.parse('test', function(err, data){
    console.log(err, value);           
});

Am I doing anything wrong?

Timing. Put f1.parse... inside the function(_app) {...}. You are using f1.parse before it is loaded.

I.e. when your file is loaded, this happens:

  • f1 is declared
  • module.exports is defined to be some function (note: the function is not executed yet, so f1 = require(...) does not happen)
  • f1.parse is called, but f1 is still undefined

EDIT: A short example, without all the Redis junk:

// a.js
module.exports = function(_app) {    
    return module.exports;
}
module.exports.parse = function (name, callback) {
    console.log("parse");
}

// b.js
module.exports = function(_app) {
    var f1 = require('./a.js')(_app);
    f1.parse('test', function(err, data){ console.log(err, value); });
};

// c.js
require('./b.js')("foo");

run node c.js, and parse comes out, no error.