Randomblue
Randomblue

Reputation: 116283

Communicating just one variable to a Node module

I have app.js and routes.js. In app.js I require routes.js. For routes.js to run, I just need to pass the single variable app to it. Is there a way to communicate app to routes.js without using require and module.exports? I'm looking for a syntax like

require(module, arguments);

Upvotes: 0

Views: 90

Answers (4)

alessioalex
alessioalex

Reputation: 63673

Think of require as a normal JavaScript function that returns a function or an object, depending on what you have.

In your case require('module') will return a function which you would then call with arguments (arg1, arg2) etc, for example:

require('module')(arg1, arg2);

You would have the following code structure in the module:

module.exports = function(arg1, arg2) {
  // your code here
}

Upvotes: 0

Kato
Kato

Reputation: 40582

In app.js:

require('module')(arg1, arg2);

And in module/index.js:

module.exports = function(arg1, arg2) {
    // code here
}

Upvotes: 0

sczizzo
sczizzo

Reputation: 3206

Similar to Xeon06's solution, if routes.js exports a function, you can usually pass in the app as a regular argument, like so: require('routes')(app).

Upvotes: 0

Alex Turpin
Alex Turpin

Reputation: 47776

Well, surely your code is wrapped into some function or class? If you have a class in routes.js

Routes = function(app) {}

Then you could do

require('routes.js');
var routes = new Routes(app);
routes.map(...);

Upvotes: 1

Related Questions