Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js namespacing

Tags:

node.js

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

like image 868
hacklikecrack Avatar asked Feb 01 '12 18:02

hacklikecrack


People also ask

What is Namespacing in JS?

Namespacing is the act of wrapping a set of entities, variables, functions, objects under a single umbrella term. JavaScript has various ways to do that, and seeing the examples will make the concept easier to understand.

What is namespace in Nodejs?

Using Namespaces Namespaces are a TypeScript-specific way to organize code. Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using outFile .

Is namespace deprecated?

While namespaces are not deprecated, using namespaces as the code organization mechanism in your code base is not always recommended.

Can not find namespace?

If you're still getting the "Cannot find namespace Context" error, open your package. json file and make sure it contains the following packages in the devDependencies object. Copied! You can try to manually add the lines and re-run npm install .


1 Answers

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();
like image 81
Jon Nichols Avatar answered Nov 15 '22 23:11

Jon Nichols