我如何要求在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得到一个文件夹的路径时,它会在该文件夹中查找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
另一种选择是使用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()
基于@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-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');
我建议使用glob来完成这个任务。
var glob = require( 'glob' )
, path = require( 'path' );
glob.sync( './routes/**/*.js' ).forEach( function( file ) {
require( path.resolve( 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
另一个选项是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`.
我知道这个问题已经有5年多了,给出的答案也很好,但我想要一些更强大的express,所以我为npm创建了express-map2包。我打算把它简单地命名为express-map,但是雅虎的人已经有了这个名字的包,所以我不得不重命名我的包。
1. 基本用法:
app.js (or whatever you call it)
var app = require('express'); // 1. include express
app.set('controllers',__dirname+'/controllers/');// 2. set path to your controllers.
require('express-map2')(app); // 3. patch map() into express
app.map({
'GET /':'test',
'GET /foo':'middleware.foo,test',
'GET /bar':'middleware.bar,test'// seperate your handlers with a comma.
});
控制器的使用方法:
//single function
module.exports = function(req,res){
};
//export an object with multiple functions.
module.exports = {
foo: function(req,res){
},
bar: function(req,res){
}
};
2. 高级用法,带前缀:
app.map('/api/v1/books',{
'GET /': 'books.list', // GET /api/v1/books
'GET /:id': 'books.loadOne', // GET /api/v1/books/5
'DELETE /:id': 'books.delete', // DELETE /api/v1/books/5
'PUT /:id': 'books.update', // PUT /api/v1/books/5
'POST /': 'books.create' // POST /api/v1/books
});
正如您所看到的,这节省了大量的时间,并使应用程序的路由非常易于编写、维护和理解。它支持所有表示支持的HTTP动词,以及特殊的.all()方法。
NPM包:https://www.npmjs.com/package/express-map2 Github回购:https://github.com/r3wt/express-map
可以使用:https://www.npmjs.com/package/require-file-directory
要求所选文件只有名称或全部文件。 不需要绝对路径。 易于理解和使用。
在这个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
要求所有文件从路由文件夹和应用作为中间件。不需要外部模块。
// require
const { readdirSync } = require("fs");
// apply as middleware
readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));
使用这个函数,你可以要求一个完整的目录。
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);
用下面的代码在文件夹中创建一个index.js文件:
const fs = require('fs')
const files = fs.readdirSync('./routes')
for (const file of files) {
require('./'+file)
}
然后你可以简单地用require("./routes")加载所有文件夹