您好,您怎么看待这种方式,导入我的所有文件(目录)以Handler.js结尾,然后全部导出
Screen of the folder where the files are
index.js:
const {join} = require('path')
const {readdirSync, readFileSync, lstatSync} = require('fs')
const handlersPath = readdirSync(__dirname)
.filter(fileName => /Handler.(js)$/.test(fileName))
.filter(fileName => !lstatSync(fileName).isDirectory())
for (const handlerPath of handlersPath){
const handlerName = /^(.*?)\Handler.js/.exec(handlerPath)[1]
exports[handlerName] = require(join(__dirname, handlerPath))
}
答案 0 :(得分:0)
const {join} = require('path')
const {readdir, lstat} = require('fs')
readdir(__dirname, (error, files) => {
if (error) throw error
for (const fileName of files){
if (!/Handler.(js)$/.test(fileName)) continue ;
lstat(fileName, (error, stats) => {
if (error) throw error
if (stats.isDirectory()) return ;
const handlerName = /^(.*?)\Handler.js/.exec(fileName)[1]
exports[handlerName] = require(join(__dirname, fileName))
})
}
})

这样完全不同步吗?