Coder Perfect

Is it true that node.js need all files in a folder?

Problem

How do I require all files in a folder in node.js?

need something like:

files.forEach(function (v,k){
  // require routes
  require('./routes/'+v);
}};

Asked by Harry

Solution #1

When a folder’s path is given to require, it looks for an index.js file in that folder; if one exists, it uses it; if not, it fails.

If you have control over the folder, it’s usually best to create an index.js file, assign all the “modules,” and then simply need that.

yourfile.js

var routes = require("./routes");

index.js

exports.something = require("./routes/something.js");
exports.others = require("./routes/others.js");

If you don’t know the filenames, you’ll need to develop a loader.

An example of a loader in action:

var normalizedPath = require("path").join(__dirname, "routes");

require("fs").readdirSync(normalizedPath).forEach(function(file) {
  require("./routes/" + file);
});

// Continue application logic here

Answered by tbranyen

Solution #2

To complete that operation, I recommend utilizing glob.

var glob = require( 'glob' )
  , path = require( 'path' );

glob.sync( './routes/**/*.js' ).forEach( function( file ) {
  require( path.resolve( file ) );
});

Answered by Diogo Cardoso

Solution #3

Base on @tbranyen’s solution, I create an index.js file that load arbitrary javascripts under current folder as part of the exports.

// Load `*.js` under current directory as properties
//  i.e., `User.js` will become `exports['User']` or `exports.User`
require('fs').readdirSync(__dirname + '/').forEach(function(file) {
  if (file.match(/\.js$/) !== null && file !== 'index.js') {
    var name = file.replace('.js', '');
    exports[name] = require('./' + file);
  }
});

Then you’ll be able to access this directory from anywhere.

Answered by Greg Wang

Solution #4

It enables you to carry out the following tasks. It also allows for recursion.

var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');

Answered by studgeek

Solution #5

I have a folder/fields full of files that all have the same class, for example:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class

To export each class, place this in fields/index.js:

var collectExports, fs, path,
  __hasProp = {}.hasOwnProperty;

fs = require('fs');    
path = require('path');

collectExports = function(file) {
  var func, include, _results;

  if (path.extname(file) === '.js' && file !== 'index.js') {
    include = require('./' + file);
    _results = [];
    for (func in include) {
      if (!__hasProp.call(include, func)) continue;
      _results.push(exports[func] = include[func]);
    }
    return _results;
  }
};

fs.readdirSync('./fields/').forEach(collectExports);

This makes the modules behave more like Python modules:

var text = new Fields.Text()
var checkbox = new Fields.Checkbox()

Answered by blented

Post is based on https://stackoverflow.com/questions/5364928/node-js-require-all-files-in-a-folder