How to manage multiple JS files server-side with Node.js
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.
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.