函数?"/>
Nodejs:在任意模块中运行函数?
假设我有一个充满 javascript 文件的目录:
.
+-- my_dir
+-- apple.js
+-- banana.js
+-- main.js
并且子目录中的每个文件都包含一个名为
setup()
.的函数
如何遍历所有文件并运行该函数?
据我所知:
var fruit = {}
var normalizedPath = require("path").join(__dirname, "fruit");
require("fs").readdirSync(normalizedPath).forEach(function(file) {
filename = file.split(".")[0] //remove the file extension
algorithms[filename] = require("./fruit/" + file); //load the file
//run the setup function in it
algorithms[filename].setup()
});
但是这样访问不到函数,返回“undefined is not a function”
回答如下:您需要从每个模块中导出
setup()
。
a-module.js
var obj = {};
obj.setup = function(){
// doStuff
}
module.exports = obj
更多推荐
Nodejs:在任意模块中运行函数?
发布评论