看一下express框架中的随机source file个,我不明白其中有两行代码(这些代码是几乎所有NodeJS文件的典型代码).

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

exports = module.exports = Router;

/**
 * Expose HTTP methods.
 */

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

I underst和 that the first piece of code allows the rest of the functions in the file to be exposed to the NodeJS app, but I don't underst和 exactly how it works, or what the code in the line means.

What do exportsmodule.exports actually mean?

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

Basically, what are these magic words: 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 scope 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

Node.js相关问答推荐

我的位置也移动时左右拖动谷歌 map

Mongoose-不会更新数组中的属性值

下一个API路由如何处理多个并发请求?

try 插入重复的邮箱时,mongoDB DuplicateKey 错误未定义

Rails 7导入npm yaml包时出现404错误

SvelteKit应用程序立即退出,没有错误

如何设置 Puppeteer Select 器的唯一性?

将 null 推入管道后,node.js 可写完成未发出

Typescript 正则表达式:过滤器返回空

未捕获的错误: 只能用作 元素的子元素,永远不会直接呈现.请将您的 包裹在

如何使用 $PATH 变量在系统中全局自动安装 bash 脚本?或者重写脚本到node

在 linux mint 上部署 node 应用程序的最简单方法是什么?

为什么 client.on("messageCreate") 的 TextChannel 中缺少 nsfw 属性?

从 Response.json() 返回的 JSON 似乎无效?

无法关闭 node.js 中的mongoose 连接

错误:找不到模块'C:\Users\nguye\AppData\Local\nodejs\node_modules\npm\bin\npm-cli.js'

为什么我的react 表单不能正常工作?

根据 mongoDB 中存在的唯一字符串生成唯一字符串的最佳方法

使用 nvm-windows 时更新 npm

JavaScript 异步编程:promise 与生成器