什么“module.exports”和“exports.methods”在NodeJS / Express中是什么意思? [英] What do "module.exports" and "exports.methods" mean in NodeJS / Express?

查看:141
本文介绍了什么“module.exports”和“exports.methods”在NodeJS / Express中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看源文件 > 框架 NodeJS ,有两行代码我不明白(这几行代码几乎是所有NodeJS文件的典型代码)。

Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files).

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

exports = module.exports = Router;

/**
 * Expose HTTP methods.
 */

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

我明白第一段代码 允许休息的文件中的功能要暴露给NodeJS应用程序,但我不明白它的工作原理,或者代码中的代码意味着什么。

I understand 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 understand exactly how it works, or what the code in the line means.


export module.exports 实际上是指?

What do exports and module.exports actually mean?

我相信第二段代码允许文件中的功能访问方法,但是又是如何做到这一点。

I believe the 2nd piece of code allows the functions in the file to access methods, but again, how exactly does it do this.

基本上,这些魔术词是什么: module export

Basically, what are these magic words: module and exports?

推荐答案

更具体地说:

module 是全球文件中的范围变量。

module is the global scope variable inside a file.

所以如果你调用 require(foo)然后:

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

它的行为方式与窗口在浏览器中动作。

It acts in the same way that window acts in the browser.

还有另一个全局对象叫做 global ,可以在任何你想要的文件中进行写入和读取,但是涉及突变全球范围,这是 EVIL

There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVIL

export 是一个变量,在 module.exports 上。当您需要一个文件时,这基本上是你导出

exports is a variable that lives on module.exports. It's basically what you export when a file is required.

// foo.js
module.exports = 42;

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

export 它是自己的。 _global范围上下文+和模块相同。 (在浏览器中,全局范围上下文和窗口是一样的)。

There is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).

// 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

了解更多有关出口的信息

这篇关于什么“module.exports”和“exports.methods”在NodeJS / Express中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆