This is the fourth post in a small series on Node.js. In this post, I will take a look at how the Node.js module mechanism works.
In my previous posts on Node.js, I nonchalantly went ahead and require(...)d something called http – but what was that? And what happened when I did that?
Well, require is one of the few globals when running a Node program, and it is used to import a module. The parameter is a string, which Node uses to look for a file to load.
The simplest usage refers directly to a file relative to the path of the currently running program. E.g., if I have a module residing in a file called importantBizLogic.js in the lib folder beneath my program’s directory, I can include its exports (which I’ll get back to in a moment :)) like so:
1 |
var biz = require('./lib/importantBizLogic'); |
If I omit the ./, Node will go look for importantBizLogic in each directory in the require.paths array, which is a list of default paths to search for modules.
Let’s see what it contains… Go to a terminal and enter the Node shell:
1 2 3 |
mogens-heller-grabes-macbook-pro:~ mhg$ node > require.paths [ '/Users/mhg/.node_modules', '/Users/mhg/.node_libraries', '/usr/local/lib/node' ] |
Great – so that’ s where my global modules reside. Now, what was that export thing again?
Well, that’s related to how importantBizLogic.js is structured… in order to control how the import works, a module must explicitly export stuff – and that can be done like so:
1 2 3 4 5 |
var secretBizConstant = 0.01; exports.calculateStuff = function(numbers) { return numbers.a + numbers.b + secretBizConstant; }; |
– allowing this module to be imported and used like so:
1 2 3 |
var biz = require('./lib/importantBizLogic'); var result = biz.calculateStuff({a: 4.15, b: 5.42}); |
Nifty!
Apparently – and I am almost embarrassed that I did not know that – there is a thing called CommonJS, which is an initiative that strives to create a JavaScript standards library – and the require stuff I’ve described here is actually just Node implementating the CommonJS Modules specification. Pretty sweet, actually!
Just wanted to say thanks for these Node posts. As a newbie trying to learn the framework, I’ve had lots of trouble that walk you through it a newbie-friendly way like you do.
Thanks, Mike The Coder. I like to be newbie-friendly when I’m a n00b myself 🙂
Nice post – cleared things up for me.
Interestingly Ryan Dahl said he would not choose CommonJS if he could choose to do things differently:
http://bostinnovation.com/2011/01/31/node-js-interview-4-questions-with-creator-ryan-dahl/