1

I have a folder in my express.js app containing three files:

// models/one.js
exports.One = function() { return 'one'; }

// models/two.js
exports.Two = function() { return 'two'; }

// models/three.js
exports.Three = function() { return 'three'; }

I'd like to be able to use it like this:

var db = require('./models');
doSomething(db.One, db.Two, db.Three);

In other words, I want to group exports from multiple files in one variable.

I know that by default that require statement will look for models/index.js. Is there anything I could put in index.js that will allow it to inherit the exports from the other files in the directory, such as (non-working psuedocode):

// models/index.js
exports = require('./one.js', './two.js', './three.js);

Thoughts? Thanks!

redtree
  • 295
  • 1
  • 2
  • 12

1 Answers1

1

See Customizing existing Module for the solution.

Or you can load all the files in a directory, e.g.

a.js:

exports.a = 1;

b.js:

exports.b = 2;

index.js: (this will require all the .js files in the same directroy and bundle them to a single object)

var fs = require('fs')
  , path = require('path')
  , bundle = {}
  , i
  , k
  , mod;

fs.readdirSync(__dirname).forEach(function(filename) {
  if (path.extname(filename) == '.js' &&
      path.resolve(filename) != __filename) {
    mod = require(path.resolve(path.join(__dirname, filename)));
    for (k in mod) {
      bundle[k] = mod[k];
    }
  }
});

module.exports = bundle;

requiring the directory you will see

{ a: 1, b: 2 }
Community
  • 1
  • 1
qiao
  • 17,941
  • 6
  • 57
  • 46
  • Note that since your using `readdirSync` this _must_ execute before the server boots – Raynos Jan 17 '12 at 12:49
  • @Raynos Would you please elaborate the reason? – qiao Jan 17 '12 at 12:52
  • Blocking IO blocks. You don't block a running single threaded server. It's acceptable to use blocking IO for a boot time convenience or for utility scripts but everything has to be non blocking once your server is accepting TCP/HTTP input. – Raynos Jan 17 '12 at 12:54