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

需要像这样的东西:

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

当前回答

如果你在example ("app/lib/*.js")目录中包含了*.js的所有文件:

在app/lib目录下

example.js:

module.exports = function (example) { }

示例- 2. - js:

module.exports = function (example2) { }

在目录app中创建index.js

index.js:

module.exports = require('./app/lib');

其他回答

使用这个函数,你可以要求一个完整的目录。

const GetAllModules = ( dirname ) => {
    if ( dirname ) {
        let dirItems = require( "fs" ).readdirSync( dirname );
        return dirItems.reduce( ( acc, value, index ) => {
            if ( PATH.extname( value ) == ".js" && value.toLowerCase() != "index.js" ) {
                let moduleName = value.replace( /.js/g, '' );
                acc[ moduleName ] = require( `${dirname}/${moduleName}` );
            }
            return acc;
        }, {} );
    }
}

// calling this function.

let dirModules = GetAllModules(__dirname);

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

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

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

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()

要求所有文件从路由文件夹和应用作为中间件。不需要外部模块。

// require
const { readdirSync } = require("fs");

// apply as middleware
readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));

当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