john smith
john smith

Reputation: 561

Understanding NodeJS's exports/require

I am playing around with node.js exports and require. Take the default express app for instance:

At the bottom of the app.js code, there is something that looks like this: app.get('/', routes.index); That means that I can have more routes specified, like this:

app.get('/login', routes.login);
app.get('/logout', routes.logout);

etc. To better understand the exports/require thing, I am trying to put those in a separate file. I am trying it this way:

//app.js
var gets = require('./gets'),
exports.foo = app;

//gets.js
var app = require('./app');
console.log(app); //returns empty obj {}

Why is it? Can you help me understand what I am doing wrong? Thanks in advance.

Upvotes: 0

Views: 131

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146164

That is what's called a circular dependency (the node docs call it a "cycle") when two modules both require each other. It is almost always a design choice you can and should avoid. Node has to load one module first, so the second one ends up getting an empty object due to this circular dependency edge case. The solution is to not make gets.js require app.js, just have app.js require gets.js.

//app.js
var app = require('express')();
var gets = require('./gets');
gets.setup(app);

then

//gets.js
function setup (app) {
    app.get('/blah', myHandler);
}
exports.setup = setup;

Upvotes: 1

Related Questions