javascript - NodeJS/Express 中的 "module.exports"和 "exports.methods"是什么意思?

标签 javascript node.js express module export

随机查看source fileNodeJSexpress 框架中,有两行代码我不明白(这些代码行是几乎所有 NodeJS 文件的典型代码)。

/**
 * Expose `Router` constructor.
 */

exports = module.exports = Router;

/**
 * Expose HTTP methods.
 */

var methods = exports.methods = require('./methods');

我了解第一段代码 允许将文件中的其余函数暴露给NodeJS应用程序,但我不完全了解< strong>它是如何工作的,或者该行中的代码是什么意思。

What do exports and module.exports actually mean?

我相信第二段代码允许文件中的函数访问方法,但同样,它究竟是如何做到这一点的。

基本上,这些神奇的词是什么:moduleexports

最佳答案

更具体一点:

module 是文件内的全局范围变量。

所以如果你调用 require("foo") 那么:

// foo.js
console.log(this === module); // true

它的作用与 window 在浏览器中的作用相同。

还有另一个名为 global 的全局对象,你可以在任何你想要的文件中写入和读取,但这涉及到改变全局范围,这就是 EVIL

exports 是一个存在于 module.exports 上的变量。它基本上是您在需要文件时导出的内容。

// foo.js
module.exports = 42;

// main.js
console.log(require("foo") === 42); // true

exports 本身存在一个小问题。 _global 范围 context+ 和 module 相同。 (在浏览器中,全局作用域上下文和 window 是一样的)。

// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with

// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports

// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works

Read more about exports

关于javascript - NodeJS/Express 中的 "module.exports"和 "exports.methods"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6116960/

相关文章:

JavaScript 标准样式无法识别 Mocha

node.js - 对于 Node.js,将所有错误处理放入针对所有未捕获异常的机制中是否有意义?

javascript - 将数据作为对象传递给 mongoDb,将其用作查询和比较

javascript - React 路由器将特定参数传递给子组件

javascript - 此 jQuery SlideUp 代码使用的正确选择器是什么?

javascript - 在 Sequelize-CLI 中仅恢复两个迁移之一?

javascript - Express.js 在 docker 容器内找不到模块 'opencv'

node.js - 如何在 Sequelize 中使用 array_agg()?

node.js - 引用错误 : DATABASE_URL is not defined when trying to connect to heroku postgres db using Sequelize

node.js - 如何使用 ExpressJS 在代理上传递 session ?