Monday, June 3, 2024
175
rated 0 times [  179] [ 4]  / answers: 1 / hits: 20273  / 13 Years ago, fri, january 27, 2012, 12:00:00

Let's say I have the following app.js (obviously very simplified):



var express = require('express'),
app = express.createServer();

// include routes
require('./lib/routes')(app);

// some random function
var foo = function() {
return 'bar';
};

// another random function
var foo2 = function() {
return 'bar2';
};


And then I have the routes module:



module.exports = function(app){
app.get('/some/route', function(req, res){
var fooBar = foo(),
fooBar2 = foo2();

res.end(fooBar + fooBar2);
});
};


This obviously doesn't work since foo and foo2 weren't defined within the module. Is there a way to make this work, or at least a different pattern to better accomplish what this?


More From » design-patterns

 Answers
13

Well you can just put these two functions in an object and pass them on the initialization of the routes.js .



var express = require('express'),
app = express.createServer();

// some random function
var foo = function() {
return 'bar';
};

// another random function
var foo2 = function() {
return 'bar2';
};

var fns = {foo : foo, foo2: foo2}

// include routes
require('./lib/routes')(app, fns);


in routes:



module.exports = function(app, fns){
app.get('/some/route', function(req, res){
var fooBar = fns.foo(),
fooBar2 = fns.foo2();

res.end(fooBar + fooBar2);
});
};


This is how would I do it. You can also include them in the app object. Beside passing them in init functions, you can also export those two functions and require them in routes.js.



var express = require('express'),
app = express.createServer();

// some random function
var foo = function() {
return 'bar';
};

// another random function
var foo2 = function() {
return 'bar2';
};

module.exports = {foo : foo, foo2: foo2}

// include routes
require('./lib/routes')(app, fns);


in routes:



module.exports = function(app){
var fns = require('../app.js');
app.get('/some/route', function(req, res){
var fooBar = fns.foo(),
fooBar2 = fns.foo2();

res.end(fooBar + fooBar2);
});
};


But I don't like the idea of it, since it makes circular dependencies. Don't have any good feelings about them.


[#87780] Wednesday, January 25, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
naya

Total Points: 60
Total Questions: 87
Total Answers: 87

Location: Guam
Member since Fri, Jun 18, 2021
3 Years ago
;