0

I am an amateur nodejs developer. I am having deep problems with javascript modules and requiring modules from inside other modules. Here is the scenario I need help with.

Lets say I have API definitions in one file like so (userApi):

var userFunctions = require('./userFunctions.js')()

module.exports = function(){

module.getUser = function(req.res){
    userFunctions.getUser(req.id, function(err,user){
      if(err) return res(err)
      return res(null,user)
    })
}

return module;
}

a helper module like so (userFunctions.js)

var paymentFunctions = require('../payment/paymentFunctions.js')()

module.exports = function(){
module.getUser = function(id,res){
//logic
}
return module;
}

another helper module like so (paymentFunctions.js)

var userFunctions = require('../user/userFunctions.js')()

module.exports = function(){
  module.makePayment = function(req,res){
    userFunctions.getUser(req.id, function(err){
      if(err) return res(err)
      return res(null)
    })
  }
return module;
}

As you can see all my helpers and APIs are inside of modules. I also put parenthesis at the end of the require statements. You might also notice that paymentFunctions requires userFunctions and vice versa. During my time with node I have yet to figure out the various errors that come with this pattern. Today I am seeing the "require is not a function error". Note: It was working and suddenly stopped working when I re indexed my webstorm project. That being said I have have many similar errors in the past with require statements and JS modules. Therefore it is a more systemic issue that I need to resolve in my brain.

1 Answers1

0

Well, I think the secret is to understand how module.exports works. First, you need to create an 'exportable' object, and then, set its properties and methods.

Something like:

var userFunctions = require('./userFunctions.js');
//Lets say this is your userApi class
module.exports = function () {
    this.getUser = function (req, res) {
        userFunctions.getUser(req.id, function (err, user) {
            if (err) return res(err)
            return res(null, user)
        });
    }
};

In this case, what I created an object (Actually a "Javascript Class") and exported it AS A module. Then, I can require it and it's methods in other places of code, since this properties are setted on the exportable object (this.prop = ...).

  • http://stackoverflow.com/questions/30576454/how-to-make-webstorm-resolve-modules-which-are-functions –  Sep 20 '16 at 06:55
  • Thanks for the help. Turns out its a problem with webstorm. I was trusting my IDE too much for this one. –  Sep 20 '16 at 07:01