Wednesday, July 20, 2011

Node.js and Modules

One of the nifty things about JavaScript is that it's finally starting to get traction as a more general-purpose programming language.  Java, for instance, uses JavaScript as it's default scripting implementation language when you're using JSR 223 scripting in Java 6.  I suppose this is payback for Java's existence butchering JavaScript's name in the first place.  We also have serverside and general application frameworks beginning to pop up like Node.js and CommonJS (these are also just beginning to emerge, so if you're looking for some interesting open source project to work with, you should check them out).

In my namespacing example, I'm going to use node.js to put together a simple server offering some services via a simple homegrown protocol.  Before I do that, I'd like to touch on how you can use the require(.) facilities node.js provides.

So node.js uses the V8 JavaScript engine to provide event-based networking services.  It also provides a require(.) function that allows you to include other JavaScript files.  It's a bit more sophisticated than a simple include though.  It requires you do develop via a specified module standard CommonJS has put together.  Personally, I would have preferred a simple include type function, but hey, this works and it's what node.js uses, so it's good enough for me.

Basically, I'm going to create side-by-side modules for the server example.  You can do this too in your work if you're using JavaScript serverside for anything.   Anyway, say we have  a simple script file defining version information; we name this version.js:

exports.version = {
major: '1',
minor: '0',
patch: '1',
status: 'gold'
}

Note the exports object.  We're using an object literal in this case, something I covered in a previous post.  We add a property to that object that contains what we're exporting. Here, I've include that information in a property named version.  Then, in the primary script file:

version = require('./version').version;

var msg = 'version is: ' 
+ version.major + '.' 
+ version.minor + '.' 
+ version.patch + ' : ' 
+ version.status;
console.log(msg);

We use the require(.) function to import the library file.  In this example, this file is console.js and it's located right next to the version.js file.  Note that we use a relative path in the module import.  I also use the convention of specifically importing a property with the same name as the file.  This isn't a requirement.

Now require(.) does allow you some namespacing functionality, but in the example I'm going over I'm going to continue to use the module pattern within my library script files.  This isn't the only way to do this, nor would I claim it's the best, but it's what I like to do.

Next, I'll begin to go into the node.js server example.

No comments:

Post a Comment