1 回答
TA贡献1772条经验 获得超6个赞
方法 2看起来不错,因为封装。
另一种可以节省大量时间的方法是在 index.js中自动导出
(对于任何服务,index.js 都是相同的,并且每次在同一目录中更改/添加模块并重新启动时都会自我更新你的服务器)
我不是代码优化专家,但这行得通
// index.js (for ALL services)
const fs = require('fs')
const path = require('path')
let fileNames = fs.readdirSync('.')
// use Sync to not create Async errors elsewere
.filter(name => name.endsWith('.js') && name !== __filename)
// only get js files and exclude this file
.map(name => './' + path.relative(__dirname, name))
// get relative paths
let methods = {}
// the future export of this file
fileNames.forEach(file => {
try {
let fileModule = require(file)
// try to require the module
Object.keys(fileModule).forEach(method => {
// for each method/key of the module
methods[method] = fileModule[method]
// add this method to the exports of this file (methods)
})
} catch (err) {
console.log('WARNING:\n' + err.message)
// probably couldn't require the module
}
})
module.exports = methods
// you export all the exported methods
// of all the js files of the same directory
显然,您应该在每个模块中仅导出“公共”方法
class FetchUser {
static filterBySomething (arg) {
// do your magik
}
static method2 (arg) {
// another method
}
}
module.exports = FetchUser
// this will make ALL methods of class FetchUser accessible in index
module.exports = {
filterBySomething: FetchUser.filterBySomething
}
// if you want other methods like method2 to NOT be exported
添加回答
举报