我如何要求在node.js文件夹中的所有文件?
需要像这样的东西:
files.forEach(function (v,k){
// require routes
require('./routes/'+v);
}};
我如何要求在node.js文件夹中的所有文件?
需要像这样的东西:
files.forEach(function (v,k){
// require routes
require('./routes/'+v);
}};
当前回答
对于这个确切的用例,我一直在使用的一个模块是require-all。
它递归地要求给定目录及其子目录中的所有文件,只要它们不匹配excludeDirs属性。
它还允许指定文件过滤器以及如何从文件名派生返回散列的键。
其他回答
如果你在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属性。
它还允许指定文件过滤器以及如何从文件名派生返回散列的键。
基于@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);
}
});
然后,您可以从其他任何地方要求这个目录。
我使用节点模块复制到模块来创建一个文件,以需要我们基于nodejs的系统中的所有文件。
我们的实用程序文件的代码是这样的:
/**
* Module dependencies.
*/
var copy = require('copy-to');
copy(require('./module1'))
.and(require('./module2'))
.and(require('./module3'))
.to(module.exports);
在所有的文件中,大多数函数都被写成export,如下所示:
exports.function1 = function () { // function contents };
exports.function2 = function () { // function contents };
exports.function3 = function () { // function contents };
所以,然后使用文件中的任何函数,你只需要调用:
var utility = require('./utility');
var response = utility.function2(); // or whatever the name of the function is
用下面的代码在文件夹中创建一个index.js文件:
const fs = require('fs')
const files = fs.readdirSync('./routes')
for (const file of files) {
require('./'+file)
}
然后你可以简单地用require("./routes")加载所有文件夹