How to manage multiple JS files server-side with Node.js

Matt Molnar picture Matt Molnar · Apr 18, 2011 · Viewed 40.9k times · Source

I'm working on a project with Node.js and the server-side code is becoming large enough that I would like to split it off into multiple files. It appears this has been done client-side for ages, development is done by inserting a script tag for each file and only for distribution is something like "Make" used to put everything together. I realize there's no point in concatting all the server-side code so I'm not asking how to do that. The closest thing I can find to use is require(), however it doesn't behave quite like script does in the browser in that require'd files do not share a common namespace.

Looking at some older Node.js projects, like Shooter, it appears this was once not the case, that or I'm missing something really simple in my code. My require'd files cannot access the global calling namespace at compile time nor run time. Is there any simple way around this or are we forced to make all our require'd JS files completely autonomous from the calling scope?

Answer

Raynos picture Raynos · Apr 18, 2011

You do not want a common namespace because globals are evil. In node we define modules

// someThings.js

(function() {
    var someThings = ...;

    ...

    module.exports.getSomeThings = function() {
        return someThings();
    }

}());

// main.js

var things = require("someThings");
...
doSomething(things.getSomeThings());

You define a module and then expose a public API for your module by writing to exports.

The best way to handle this is dependency injection. Your module exposes an init function and you pass an object hash of dependencies into your module.

If you really insist on accessing global scope then you can access that through global. Every file can write and read to the global object. Again you do not want to use globals.