Sunday, July 3, 2011

A simple intro to NodeJS modules

In preparation for an upcoming workshop at Shad Valley on NodeJS, I tried to come up with some simple examples of the CommonJS module system in NodeJS.  Felix Geisendörfer has a similar "hello world" example in his Node.js Beginner Guide.  I've put the main concepts into a short tutorial. We start with one line of Javascript, and turn it into a working NodeJS module.

Assuming you have node installed, you can run "node" from the command line to get the REPL (ie. node shell).

$ node
> console.log("Hello World!");
Hello World!

Wonderful. How about putting this in a file?
// hello.js
console.log("Hello World!")

Then run:
$ node hello.js
Hello World!

Also wonderful. Then, how about making an application that includes hello.js? Let's call it app.js. Here are the two files:

// app.js
require('./hello.js');

// hello.js
console.log("Hello World!");

Now we can run it like this.
$ node app.js
Hello World!

Again wonderful. We've written a module. Not a very fancy one, but it's a start. Now, as an aside, suppose we want to run app.js like a shell script, without specifying "node" on the command line all the time? Simply add the node command to the app.js script:

#!/usr/bin/env node
// app.js
require('./hello.js');

Oh, and make it executable.
chmod u+x app.js

Now we can run it like so:
$ ./app.js
Hello World!

Now we can begin having fun. The thing about modules is that whatever you declare in the module (hello.js) is local to that module. If you want to use it externally, you have to add it to the special variable "exports":

// hello.js
var greeting = "Hello World!";
var greet = function() {
   console.log(greeting);
}
exports.greet = greet;

#!/usr/bin/env node
// app.js
var mygreet = require('./hello.js').greet;
mygreet();

This accomplishes the same thing, but take note of a couple things. First, "var greeting" is not available outside of the hello.js file. The function "greet" is available though, because we added it to exports. So that's how you get variables, functions and objects to be available from your module. Easy peasy.

1 comment:

Unknown said...

this is a very nice intro for commonjs, thanks

Productivity and Note-taking

I told a friend of mine that I wasn't really happy with the amount of time that gets taken up by Slack and "communication and sched...