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

Javascriptnode.jsDevelopment Environment

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

re @Raynos answer, if the module file is next to the file that includes it, it should be

var things = require("./someThings");

If the module is published on, and installed through, npm, or explicitly put into the ./node_modules/ folder, then the

var things = require("someThings");

is correct.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt MolnarView Question on Stackoverflow
Solution 1 - JavascriptRaynosView Answer on Stackoverflow
Solution 2 - JavascriptmichielbdejongView Answer on Stackoverflow