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

需要像这样的东西:

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

当前回答

基于@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);
  }
});

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

其他回答

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

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

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

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

在这个glob解决方案上展开。如果你想将所有模块从一个目录导入到index.js中,然后将该index.js导入到应用程序的另一部分,那么就这样做。注意,stackoverflow使用的高亮显示引擎不支持模板文字,因此这里的代码可能看起来很奇怪。

const glob = require("glob");

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  /* see note about this in example below */
  allOfThem = { ...allOfThem, ...require(file) };
});
module.exports = allOfThem;

完整的示例

目录结构

globExample/example.js
globExample/foobars/index.js
globExample/foobars/unexpected.js
globExample/foobars/barit.js
globExample/foobars/fooit.js

globExample - js操作。

const { foo, bar, keepit } = require('./foobars/index');
const longStyle = require('./foobars/index');

console.log(foo()); // foo ran
console.log(bar()); // bar ran
console.log(keepit()); // keepit ran unexpected

console.log(longStyle.foo()); // foo ran
console.log(longStyle.bar()); // bar ran
console.log(longStyle.keepit()); // keepit ran unexpected

globExample foobars / index . js

const glob = require("glob");
/*
Note the following style also works with multiple exports per file (barit.js example)
but will overwrite if you have 2 exports with the same
name (unexpected.js and barit.js have a keepit function) in the files being imported. As a result, this method is best used when
your exporting one module per file and use the filename to easily identify what is in it.

Also Note: This ignores itself (index.js) by default to prevent infinite loop.
*/

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  allOfThem = { ...allOfThem, ...require(file) };
});

module.exports = allOfThem;

globExample foobars /无法js。

exports.keepit = () => 'keepit ran unexpected';

globExample foobars / barit js。

exports.bar = () => 'bar run';

exports.keepit = () => 'keepit ran';

globExample foobars / fooit js。

exports.foo = () => 'foo ran';

在安装了glob的项目中,运行node example.js

$ node example.js
foo ran
bar run
keepit ran unexpected
foo ran
bar run
keepit ran unexpected

如果你在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');

对于这个确切的用例,我一直在使用的一个模块是require-all。

它递归地要求给定目录及其子目录中的所有文件,只要它们不匹配excludeDirs属性。

它还允许指定文件过滤器以及如何从文件名派生返回散列的键。