我如何要求在node.js文件夹中的所有文件?

需要像这样的东西:

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

当前回答

我有一个文件夹/字段的文件与单个类每个,例如:

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

把它放到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);

这使得模块的行为更像在Python中:

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

其他回答

基于@tbranyen的解决方案,我创建了一个index.js文件,在当前文件夹下加载任意javascript作为导出的一部分。

// 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);
  }
});

然后,您可以从其他任何地方要求这个目录。

当require得到一个文件夹的路径时,它会在该文件夹中查找index.js文件;如果有一个,它就使用它,如果没有,它就失败。

这可能是最有意义的(如果你可以控制文件夹)创建一个index.js文件,然后分配所有的“模块”,然后简单地要求。

yourfile.js

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

index.js

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

如果你不知道文件名,你应该写一些加载器。

加载器的工作示例:

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

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

// Continue application logic here

可以使用:https://www.npmjs.com/package/require-file-directory

要求所选文件只有名称或全部文件。 不需要绝对路径。 易于理解和使用。

另一种选择是使用require-dir包,它允许您执行以下操作。它也支持递归。

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

另一个选项是require-dir-all,它结合了大多数流行包的特性。

最流行的require-dir没有过滤文件/dirs的选项,也没有映射函数(见下文),但使用小技巧来查找模块的当前路径。

其次受欢迎程度require-all有regexp过滤和预处理,但缺乏相对路径,所以你需要使用__dirname(这有优点和缺点),像这样:

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

这里提到的require-index是非常简洁的。

使用map你可以做一些预处理,比如创建对象和传递配置值(假设下面的模块导出构造函数):

// Store config for each module in config object properties 
// with property names corresponding to module names 
var config = {
  module1: { value: 'config1' },
  module2: { value: 'config2' }
};

// Require all files in modules subdirectory 
var modules = require('require-dir-all')(
  'modules', // Directory to require 
  { // Options 
    // function to be post-processed over exported object for each require'd module 
    map: function(reqModule) {
      // create new object with corresponding config passed to constructor 
      reqModule.exports = new reqModule.exports( config[reqModule.name] );
    }
  }
);

// Now `modules` object holds not exported constructors, 
// but objects constructed using values provided in `config`.