Node.js namespacing


Struggling a little to make best use of Node’s module/require()/exports set up to do proper OO programming. Is it good practice to create global namespace and not use exports (as in client side js app development)? So, in module (Namespace.Constructor.js):

Namespace = Namespace || {};
Namespace.Constructor = function () {
Namespace.Constructor.prototype.publicMethod = function () {
// blah blah

… and in calling file just use…

var object = new Namespace.Constructor();


Problem courtesy of: hacklikecrack


In node.js, the module location is the namespace, so there’s no need to namespace in the code as you’ve described. I think there are some issues with this, but they are manageable. Node will only expose the code and data that you attach to the module.exports object.

In your example, use the following:

var Constructor = function() {
// initialize
Constructor.prototype.publicMethod = function() {}
module.exports = Constructor;

And then, in your calling code:

var Constructor = require('./path/to/constructor.js');
var object = new Constructor();

Solution courtesy of: Jon Nichols

View additional discussion.