require-context-async
v1.2.1
Published
express require.context
Downloads
10
Readme
requireContext
node中的实现类似require.context
install
npm install --save require-context-async
options
requireContext(directory, useSubdirectories = false, regExp = /\.js$/, fn);
directory {String} -读取文件的路径
useSubdirectories {Boolean} -是否遍历文件的子目录
regExp {RegExp} -匹配文件的正则
fn {Function} -执行每次迭代回调 可选参数
demo
router/user.router.js
const router = require('express').Router();
router.param('id', function (req, res, next, candidate) {
const validator = !isNaN(parseFloat(candidate)) && isFinite(candidate);
if (validator) {
next()
} else {
res.sendStatus(403)
}
})
router.route('/user/:id').get( function (req, res) {
res.send('OK')
})
module.exports = router;
app.js
const express = require('express');
const path = require('path');
const app = express();
const requireContext = require('require-context-async');
let files = requireContext(path.resolve(__dirname, './router'), false, /.js$/, (item) => {
app.use(require(item));
});
console.log(files)