最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Nodejs:在任意模块中运行函数?

网站源码admin44浏览0评论

Nodejs:在任意模块中运行函数?

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
发布评论

评论列表(0)

  1. 暂无评论