Salvador Dali
Salvador Dali

Reputation: 222541

How to use function from one custom module in another custom module

I have a following project structure

|server
|- module1.js
|- module2.js
|app.js

module1.js looks this way

module.exports = {
    f1 : function(){ ... },
    ...
    fN : function(){ ... }
};

module2.js looks this way

module.exports = {
    t1 : function(){ ... }, 
    ...
    tN : function(){ ... }
};

In app.js I use both of these modules

var M1 = require('./module1.js');
var M2 = require('./module2.js');

So right now I can use M1.f1(), M2.t1(). The problem is that in module2 I have to use functions from module1. If I define t1 as function(){ M2.f1(); .... } it generates an error telling that M2 is not defined.

How can I fix it? (I know that I can require module2 in module1, but it just doesn't feel right)

Upvotes: 0

Views: 172

Answers (2)

Matthew Bakaitis
Matthew Bakaitis

Reputation: 11980

1) Require M1 in M2. Not sure why you don't think it "feels right" but it's a legitimate way to handle it.

2) After you declare M1 - require('./module1.js');, pass M1 into M2 so it can be used in M2. This will give you access to the properties there. You'd wind up with something looking like var M2 = require('./module2.js')(M1). In my opinion, this starts to complicate things more than the require in #1...

3) If you want the same function in both...then maybe you need a third module. This third module would export the functions that both M1 and M2 will expose as methods.

This third way is probably the best if you find yourself with a bunch of commonly used functions that aren't tightly coupled to one or another object. Creating a utility module that exports these common functions (file or database functions are examples) for reuse in others is a common approach.

Note that you'd wind up requiring this third module in both of the original two...which I think is reasonable given the way the code would be organized so that you were requiring a 'utility library' that is used by the other two modules.

Upvotes: 1

mscdex
mscdex

Reputation: 106696

The other option (besides requiring module1 in module2) would be to pass the functions in to module2:

// module2.js
module.exports = function(mod1) {
  // use mod1.f1, ..., mod1.fN anywhere in here
  return {
    t1 : function(){ ... },
    tN : function(){ ... }
  };
};

// main.js
var M1 = require('./module1.js');
var M2 = require('./module2.js')(M1);

Upvotes: 1

Related Questions