Javascript NodeJS / Express 中的“module.exports”和“exports.methods”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6116960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:18:36  来源:igfitidea点击:

What do "module.exports" and "exports.methods" mean in NodeJS / Express?

javascriptnode.jsexpressmoduleexport

提问by mrwooster

Looking at a random source fileof the expressframework 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).

看着一个随机的源文件中的express为框架NodeJS,也有代码,我不明白的两行(这行代码是典型的几乎所有文件的NodeJS)。

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

exports = module.exports = Router;

and

/**
 * Expose HTTP methods.
 */

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

I understand that the first piece of codeallows 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.

我知道第一段代码允许文件中的其余函数暴露给 NodeJS 应用程序,但我不明白如何工作的,或者行中的代码意味着什么。

What do exportsand module.exportsactually mean?

什么exportsmodule.exports实际上的意思吗?

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

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

Basically, what are these magic words: moduleand exports?

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

回答by Raynos

To be more specific:

更具体:

moduleis the global scope variable inside a file.

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

So if you call require("foo")then :

所以如果你打电话require("foo")

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

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

它的行为方式window与浏览器中的行为方式相同。

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

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

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

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

// foo.js
module.exports = 42;

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

There is a minor problem with exportson it's own. The _global scope context+ and moduleare notthe same. (In the browser the global scope context and windoware the same).

exports它自己有一个小问题。在_global范围上下文+和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

阅读有关出口的更多信息

回答by Tamzin Blake

To expand on Raynos's answer...

扩展雷诺斯的答案......

exportsis basically an aliasfor module.exports- I recommend just not using it. You can expose methods and properties from a module by setting them on module.exports, as follows:

exports基本上是一个别名module.exports-我建议只是不使用它。您可以通过将方法和属性设置为 onmodule.exports公开模块中的方法和属性,如下所示:

//file 'module1.js'
module.exports.foo = function () { return 'bar' }
module.exports.baz = 5

Then you get access to it in your code:

然后你可以在你的代码中访问它:

var module1 = require('module1')
console.log(module1.foo())
console.log(module1.baz)

You can also overridemodule.exportsentirely to simply provide a single object upon require:

您还可以module.exports完全覆盖以根据需要简单地提供单个对象:

//glorp.js
module.exports = function () {
  this.foo = function () { return 'bar' }
  this.baz = 5
  return this // need to return `this` object here
}

Now you've got a nice prototype:

现在你有了一个不错的原型:

var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)

There are myriad other ways to play with module.exportsand require. Just remember, require('foo')always returns the same instanceeven if you call it multiple times.

还有无数其他方法可以使用module.exportsrequire。请记住,即使您多次调用它,也require('foo')始终返回相同的实例

Note

笔记

For the following to work,

为了以下工作,

var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz) 

thishas to be returned in the function that is assigned to module.exports. Otherwise, you'll get a TypeError:

this必须在分配给 的函数中返回module.exports。否则,你会得到一个TypeError

console.log(g1.foo())
          ^
TypeError: Cannot read property 'foo' of undefined

回答by jeremyko

You can find the best answer in node.js source code. If someone is requiring your js module, your script turns into a function by node as follows (see src/node.js).

您可以在 node.js 源代码中找到最佳答案。如果有人需要你的 js 模块,你的脚本会按节点变成一个函数,如下所示(参见 src/node.js)。

// require function does this..
(function (exports, require, module, __filename, __dirname) {
    ... your javascript contents...
});

Node will wrap your script. Then above script will be executed as follows:

Node 将包装您的脚本。然后上面的脚本将按如下方式执行:

//module.js
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);

So in your script,

所以在你的脚本中,

exports is just module.exports.

In your script, you can add something to this exports object (functions..). require function will return this object. This is node.js's module system (commonJS specification).

在您的脚本中,您可以向此导出对象(函数..)添加一些内容。require 函数将返回这个对象。这是 node.js 的模块系统(commonJS 规范)。

But be careful not to modify module.exports. Otherwise your current exports will be meaningless.

但是注意不要修改module.exports。否则,您当前的导出将毫无意义。

回答by Josh

module is an object that represents what that particular source file would like to publicly expose. Instead of having something akin to header files in the c/c++ world, you describe what the module exportsby defining this object. the node runtime then uses this object to determine what about your module is 'public.'

模块是一个对象,表示特定源文件想要公开的内容。您不必使用类似于 c/c++ 世界中的头文件的内容,而是通过定义此对象来描述模块导出的内容。然后节点运行时使用这个对象来确定你的模块是“公共”的。

its a similar concept to exporting functions from a dll in the compiled world. you have to define explicitly what functions can be accessed by the outside world. this helps with encapsulation and lets your organize your libraries in a clean way.

它类似于从编译世界中的 dll 导出函数的概念。您必须明确定义外部世界可以访问哪些函数。这有助于封装并让您以干净的方式组织您的库。

回答by Pablo Andres Diaz Mazzaro

Module's code is wrapped in module.exports(The module, maybe composed by other module). There are many ways to build a module, but this is one very common (and my personal favorite).

模块的代码被封装在module.exports(该模块,可能由其他模块组成)。构建模块的方法有很多种,但这是一种非常常见的(也是我个人最喜欢的)。

// Dependencies
// const module = require('module');

// Module object
var foo = {}

// Internal property
foo._a = 'a';

// "Public" property
foo.b = 'b';

// Method
foo.fu = function() { return 'fu' };

// Export
module.exports = foo;