Keeping “require” modules DRY in Node

Update: See the follow-up on StackOverflow. I agree with those who rallied against use of global, but no need to throw the baby out with the bathwater; as shown in that thread, we can instead use “eval” to keep it DRY.

You see a lot of NodeJS code like this:

javascript

  1. connect = require 'connect'
  2. express = require 'express'
  3. redis = require 'redis'
  4. sys = require 'sys'
  5. coffee = require 'coffee-script'
  6. fs = require 'fs'

BTW this is CoffeeScript, not pure JavaScript, but the same logic applies.

The point is, Node’s module system gives you a layer of abstraction you probably don’t need. 9 times out of 10, people just assign a module to a variable by the same name. You would, wouldn’t you?!! You don’t have to think about alternatives, and you can easily cut and paste other people’s code. And it’s now just an industry convention.

So why not practice convention over configuration, and keep things DRY with the following idiom:

javascript

  1. "underscore,connect,express,redis,sys,coffee-script,fs"
  2.   .split(',').forEach (lib) -> global[lib] = require lib

Thanks to the “global” object, which is like the “window” object in the browser, we can easily require new libraries without unnecessary clutter.

And – as with any decent convention-over-configuration setup – we can still override the convention if we desire:

javascript

  1. _ = underscore