这种导出文件的方法是否正确?

时间:2017-08-10 10:55:40

标签: javascript node.js fs

您好,您怎么看待这种方式,导入我的所有文件(目录)以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))
}

1 个答案:

答案 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))
		 
	   })
	}
})




这样完全不同步吗?