Node.js module.exports的目的是什么,你如何使用它? [英] What is the purpose of Node.js module.exports and how do you use it?
问题描述
Node.js module.exports的目的是什么?你如何使用它?
What is the purpose of Node.js module.exports and how do you use it?
我似乎找不到任何关于此的信息,但它似乎是Node.js的一个相当重要的部分,因为我经常在源代码中看到它。
I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.
根据 Node.js文档:
模块
对当前
模块的引用
。特别是 module.exports
与exports对象相同。有关详细信息,请参阅
src / node.js
。
但这并没有什么帮助。
module.exports
究竟做了什么,以及一个简单的例子是吗?
What exactly does module.exports
do, and what would a simple example be?
推荐答案
module.exports
是由于 require
调用而实际返回的对象。
module.exports
is the object that's actually returned as the result of a require
call.
exports
变量最初设置为同一个对象(即它是速记别名),所以在模块代码中,你通常会写这样的东西:
The exports
variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:
var myFunc1 = function() { ... };
var myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
导出(或公开)内部作用域函数 myFunc1
和 myFunc2
。
to export (or "expose") the internally scoped functions myFunc1
and myFunc2
.
在调用代码中你会使用:
And in the calling code you would use:
var m = require('./mymodule');
m.myFunc1();
其中最后一行显示的结果如何
(通常)只是一个可以访问其属性的普通对象。
where the last line shows how the result of require
is (usually) just a plain object whose properties may be accessed.
注意:如果你覆盖 exports
那么它将不再引用 module.exports
。因此,如果您希望将新对象(或函数引用)分配给 exports
,那么您还应该将该新对象分配给 module.exports
NB: if you overwrite exports
then it will no longer refer to module.exports
. So if you wish to assign a new object (or a function reference) to exports
then you should also assign that new object to module.exports
值得注意的是,添加到 exports $的名称c $ c> object不必与您要添加的值的模块内部范围名称相同,因此您可以:
It's worth noting that the name added to the exports
object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:
var myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
后跟:
var m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
这篇关于Node.js module.exports的目的是什么,你如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!