node介绍读取文件目录实现去中心化管理路由后台最近在写一个node项目发现路由太多,手动require不符合程序员的气质。为了偷懒,只能自己写一段代码自动导入。目录结构│─app.js//入口文件│─router//路由文件夹││─router.js//集中式路由│├─V1//版本文件││└─test.js//路由│└─V2│└─test.js│utils└─requireContext.js//实用函数app.js//app.js代码constKoa=require('koa')constroutes=require('./router/router.js')constapp=newKoa()//挂载路由app.use(routes)app.listen(3000)router.js//router/router.js作为集中路由constpath=require('path')constcompose=require('koa-compose')constrequireContext=require('../utils/requireContext.js')//原创写法/*constroutes=compose([//需要导入所有路由require('./V1/test.js').routes(),require('./V1/test.js').routes(),])*///现在的写法是新的,不再需要路由文件donemanuallyimported//参数1文件路径//参数2regular这里是router.js末尾的所有js//参数3递归子目录letfiles=requireContext(path.resolve(__dirname,'./'),/(?require(item).routes()))//导出路由中间件集合module.exports=routesest.js//router/V1/test.jsrouter/V2/test.jsconstRouter=require('koa-router')constrouter=newRouter()router.prefix('/V2')router.get('/test',(ctx,next)=>{ctx.body='hello'})//导出路由module.exports=routerrequireContext.js//文件加载去中心化constfs=require('fs')constpath=require('path')/***@param{String}filePath目录绝对路径*@param{Regexp}filtersfilter*@param{Boolean}deep是否遍历子目录*@returns{Array}*/functionrequireContext(filePath,filters,deep){//文件直接退出if(fs.statSync(filePath).isFile()){return[filePath]}//过滤器不规则if(filters&&!(filtersinstanceofRegExp)){thrownewError('filtersmustRegexp')}letfilesArray=[]findFile(filePath,deep,filesArray)returnfilters?filesArray.filter(item=>filters.test(item)):filesArray}functionfindFile(filePath,deep,filesArray){letfiles=fs.readdirSync(filePath)files.forEach(item=>{letfPath=path.resolve(filePath,item)if(fs.statSync(fPath).isFile()){filesArray.push(fPath)}elseif(deep){findFile(fPath,deep,filesArray)}})}module.exports=requireContext
