// 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 这个目录 .
1
我有一个文件夹/字段,每个文件都有一个类,ex:
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()
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`.
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. advanced usage, with prefixes:
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
});
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
11 回答
另一种选择是使用包require-dir,让你做以下事情 . 它也支持递归 .
当require被赋予文件夹的路径时,它将在该文件夹中查找index.js文件;如果有,则使用它,如果没有,则失败 .
最有意义的是(如果你可以控制文件夹)创建一个index.js文件,然后分配所有“模块”然后只需要它 .
yourfile.js
index.js
如果你不知道文件名,你应该写一些加载器 .
装载机的工作示例:
我建议使用glob来完成该任务 .
基于@tbranyen的解决方案,我创建了一个
index.js
文件,它在当前文件夹下加载任意javascripts,作为exports
的一部分 .然后你可以从任何其他地方
require
这个目录 .我有一个文件夹/字段,每个文件都有一个类,ex:
将它放在fields / index.js中以导出每个类:
这使得模块的行为更像Python中的模块:
还有一个选项是require-dir-all结合了大多数流行软件包的功能 .
最流行的
require-dir
没有筛选文件/目录的选项,也没有map
函数(见下文),但使用小技巧查找模块的当前路径 .第二个受欢迎
require-all
有正则表达式过滤和预处理,但缺少相对路径,所以你需要使用__dirname
(这有利弊),如:这里提到的
require-index
非常简约 .使用
map
,您可以执行一些预处理,例如创建对象和传递配置值(假设模块在导出构造函数下面):我一直用于这个确切用例的一个模块是require-all .
它递归地要求给定目录及其子目录中的所有文件,只要它们与
excludeDirs
属性不匹配 .它还允许指定文件过滤器以及如何从文件名派生返回的哈希的键 .
我知道这个问题是5年了,而且给出的答案都很好,但我想要一些更强大的表达,所以我为npm创建了
express-map2
包 . 我打算简单地命名它express-map
,但雅虎的人已经有了一个包含该名称的包,所以我不得不重命名我的包 .1. basic usage:
控制器用法:
2. advanced usage, with prefixes:
正如您所看到的,这节省了大量时间,并使您的应用程序的路由变得简单,无法编写,维护和理解 . 它支持所有表达支持的http动词,以及特殊的
.all()
方法 .npm包:https://www.npmjs.com/package/express-map2
github回购:https://github.com/r3wt/express-map
我正在使用node modules copy-to module创建一个文件来要求我们基于NodeJS的系统中的所有文件 .
our utility file的代码如下所示:
在所有文件中,大多数函数都写为导出,如下所示:
那么,要使用文件中的任何函数,只需调用:
可以使用:https://www.npmjs.com/package/require-file-directory
要求选择仅包含名称的文件或所有文件 .
不需要absoulute路径 .
易于理解和使用 .
如果在目录示例中包含* .js的所有文件(“app / lib / * .js”):
在目录app / lib中
example.js:
例如,2.js:
在目录应用中创建index.js
index.js: