【问题标题】:Can someone explain how i can use module.exports this way有人可以解释我如何以这种方式使用 module.exports
【发布时间】:2017-12-14 16:01:40
【问题描述】:

我试图了解在模型视图控制器类型项目中将 module.exports 与变量一起使用时发生了什么。我只是不明白以这种方式使用这本书是什么意思

var express = require("./config/express.js");
var app = express();

app.listen(3000);
module.exports = app; // my problem is right here what is it doing 

console.log("Server running at http://localhost:3000/");

我的 config/ express 文件也在这里

var express = require("express");

module.exports = function()
{
  var app = express();


  require("../app/routes/index.server.routes.js")(app);
  return app;  
}

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

第一个示例是直接导出 Express 应用,第二个示例是导出 返回 Express 应用的 函数

这意味着在第一个示例中,require(...) 将返回 app。在第二个示例中,您需要执行 require(...)() 才能返回 app

【讨论】:

  • 所以我在 module.exports = app 中暴露了应用程序;
  • 是的,直接。无论您设置为 module.exports 什么都是在该模块上调用 require() 时将返回的内容。默认情况下,这是一个普通(空)对象,等于 exports 变量。
  • 为什么要在 module.exports = app 中暴露应用
  • 对此没有真正的答案。这主要是个人喜好。您可以随心所欲地导出任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-18
  • 2013-11-30
  • 1970-01-01
相关资源
最近更新 更多