Taking Baby Steps with Node.js – “node_modules” Folders

Here are the links to the previous installments:

  1. Introduction
  2. Threads vs. Events
  3. Using Non-Standard Modules
  4. Debugging with node-inspector
  5. CommonJS and Creating Custom Modules
  6. Node Version Management with n
  7. Taking Baby Steps with Node.js ? Implementing Events
  8. BDD Style Unit Tests with Jasmine-Node Sprinkled With Some Should

For this post I want to quickly share a nice addition to Node.js that is available since version 4.0.x. In the previous post, I provided some example code of BDD style unit tests that make use of the should.js library that enabled us to use BDD style assertions. We loaded the ?should? module just as if it was a native module:

var should = require('should');

In order to accomplish the same using version 0.2.x of Node.js, we needed to either prefix a relative path:

var should = require('./../dependencies/should');

or add our dependencies folder to the require.paths:

require.paths.push(__dirname + './../dependencies/');
var should = require('should');

When you omit the ?/?, ?../? or ?./? prefix for loading a non-native module using version 4.0.x, then Node.js will automatically start searching in the parent directory of the current module for a folder named ?node_modules? and tries to load the requested module from that location on disk. If it cannot be found there, then it goes up one level again and repeats the same process until the module is found or until the root folder is reached.

For that reason I renamed all my ?dependencies? folders to ?node_modules? so I that I?m able to incorporate third-party modules more easily.

This might not sound like a big deal, and it certainly isn?t, but this small new feature already reduced a good number of WTF?s on my end ;-). 

Until next time.

2 thoughts on “Taking Baby Steps with Node.js – “node_modules” Folders

  1. You could achieve the same (using your own modules w/o require(‘../../blah’) by packaging them as NPM packages. Private NPM packages don’t have to be published on the public NPM repository, because NPM can install from a source tree (npm install .) or tarball. On the other hand this is lighter weight than using NPM.

  2. The upcoming npm 1.0 release incorporates the same folder when installing packages locally. I’m going to write a blog post about this and the other new features of npm 1.0 very soon.

Comments are closed.

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.