Node.js namespacing

Problem

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 () {
//initialise
}
Namespace.Constructor.prototype.publicMethod = function () {
// blah blah
}

… and in calling file just use…

requires('Namespace.Constructor');
var object = new Namespace.Constructor();
object.publicMethod();

Thanks

Problem courtesy of: hacklikecrack

Solution

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();
object.publicMethod();

Solution courtesy of: Jon Nichols

View additional discussion.