Global variables for node.js standard modules?

ajsie picture ajsie · Nov 10, 2010 · Viewed 65.7k times · Source

I know that global variables are bad.

But if I am using node's module "util" in 40 files in my framework, isn't it better to just declare it as a global variable like:

util = require('util');

in the index.js file instead of writing that line in 40 files?

Cause I often use the same 5-10 modules in each file, that would save a lot of time instead of copy paste all the time.

Isn't DRY good in this case?

Answer

Robin Duckett picture Robin Duckett · Nov 24, 2010

You could just have a common module.

common.js:

Common = {
  util: require('util'),
  fs:   require('fs'),
  path: require('path')
};

module.exports = Common;

app.js:

var Common = require('./common.js');
console.log(Common.util.inspect(Common));