6

I've got really strange behavior of require() in node.js.

I have simple common.js:

module.exports = common = {
    config: require('./config/config'),
    errorCodes: require('./config/errorCodes'),
    server: require('./server/server').server,
    dbManager: require('./db/dbManager').dbManager,
    idGenerator: require('./utils/idGenerator').idGenerator
};

my server.js:

var http = require('http'),
    url = require("url"),
    common = require('../common');

var server = (function ()
{
    var server = http.createServer(function (request, response)
    {

    });

    // running server
    function startServer()
    {
        server.listen(common.config.port);
        console.log('Tracking server running at :' + common.config.port);
    }

    return {
        startServer: startServer
    };
})();

module.exports.server = server;

So, Case 1, - I'm reqiuring common only in server.js, it works:

start.js:

//var common = require('./common');
var server = require('./server/server').server;

// initialize whole server
var init = function ()
{
//    common.dbManager.init();
    server.startServer();
};

init();

And, Case 2, I'm requiring common in both modules - doesn't work:

start.js

var common = require('./common');
var server = require('./server/server').server;

// initialize whole server
var init = function ()
{
    common.dbManager.init();
    server.startServer();
};

init();

The error is that in the second case certain properies common.config and common.dbManager are undefined. Does anybody have an idea why?

Thanks in advance.

Update

Thanks guys, the following solution works:

Your 'common' model is not needed: just require modules you need explicitly

1 Answer 1

10

You have a cycle: server -> common -> server. Node.js require() returns undefined (by design) when module that is being loaded is required again, in cycle.

Solve your cycle.

Sign up to request clarification or add additional context in comments.

2 Comments

If you can't live without the cycle, than at least move actual code (like the init) in process.nextTick(), or even better, have one place where you call the initialization manually. Your 'common' model is not needed: just require modules you need explicitly. They are cached, so no performance loss.
I believe you're right. I'll check tomorrow and let you guys know the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.