require-all / 1.1.0 last updated 3 months ago created on Dec 14th 2011

Install

npm install --save require-all

Clone

git clone git@github.com:felixge/node-require-all.git

dependencies

No dependencies listed.

maintainers

felixge felixge
thlorenz thlorenz
dscape dscape
dougwilson dougwilson

versions 9 total

1.1.0 3 months ago dougwilson
1.0.0 9 months ago dougwilson
0.0.8 2 years ago dscape
0.0.6 2 years ago thlorenz
0.0.5 3 years ago thlorenz
0.0.4 3 years ago felixge
0.0.3 4 years ago felixge
0.0.2 4 years ago felixge
0.0.1 4 years ago felixge
17629 Downloads yesterday.

readme

require-all

An easy way to require all files within a directory.

Usage

1
2
3
4
5
6
7
8
9
var controllers = require('require-all')({
  dirname     :  __dirname + '/controllers',
  filter      :  /(.+Controller)\.js$/,
  excludeDirs :  /^\.(git|svn)$/
});

// controllers now is an object with references to all modules matching the filter
// for example:
// { HomeController: function HomeController() {...}, ...}

Advanced usage

If your objective is to simply require all .js and .json files in a directory you can just pass a string to require-all:

var libs = require('require-all')(__dirname + '/lib');

Constructed object usage

If your directory contains files that all export constructors, you can require them all and automatically construct the objects using resolve:

1
2
3
4
5
6
7
8
var controllers = require('require-all')({
  dirname     :  __dirname + '/controllers',
  filter      :  /(.+Controller)\.js$/,
  excludeDirs :  /^\.(git|svn)$/,
  resolve     : function (Controller) {
    return new Controller();
  }
});

Alternative property names

If your directory contains files where the names do not match what you want in the resulting property (for example, you want camelCase but the file names are snake_case), then you can use the map function:

var controllers = require('require-all')({
  dirname     :  __dirname + '/controllers',
  filter      :  /(.+Controller)\.js$/,
  excludeDirs :  /^\.(git|svn)$/,
  map         : function (name, path) {
    return name.replace(/_([a-z])/g, function (m, c) {
      return c.toUpperCase();
    });
  }
});
Resolving all dependencies.. This could take a while as our cache is not yet fully warmed up.