了解NodeJS中的导出

typ*_*ror 5 node.js

我不认为我完全理解Node.js中的exports工作方式.在一些示例代码中,我注意到以这种方式使用的对象:exports

exports = mongoose = require('mongoose')
mongoose.connect(config.db.uri)
exports = Schema = mongoose.Schema
Run Code Online (Sandbox Code Playgroud)

你使用exports =两次这样的幕后发生了什么?在我看来,"mongoose"不应该被导出.我做了这个快速测试:

var foo
  , bar

exports = foo = 'foo'
exports = bar = 'bar'

// reports 'bar' only
console.log(exports)
Run Code Online (Sandbox Code Playgroud)

第二次测试会覆盖第一次导出.

Pet*_*ons 15

我的猜测是该示例代码的原始作者对module.exportsvs 感到困惑exports.要使用该exports对象,必须向其添加属性,如下所示:

exports.size = 42;
Run Code Online (Sandbox Code Playgroud)

如果将exports 变量重新分配给新对象,则基本上无法访问node.js为您提供的全局导出对象.如果这样做两次或三次或N次,效果是一样的.这毫无用处.例如:mod_b.js

var realExports = exports;
realExports.height = 42;
var exports = {};
exports.weight = 43;
Run Code Online (Sandbox Code Playgroud)

在mod_a.js中

var mod_b = require('./mod_b');
console.dir(mod_b);
Run Code Online (Sandbox Code Playgroud)

node mod_a.js,你得到:

{ height: 42 }
Run Code Online (Sandbox Code Playgroud)

注意到了height,但weight没有.现在,您可以做的是分配module.exports为一个对象,这是当另一个模块require是您的模块时将返回的对象.所以你会看到类似的东西.

var x = 10;
var y = 20;
module.exports = {x: x, y: y};
Run Code Online (Sandbox Code Playgroud)

哪个会做你期望的.这里有一些关于细节的信息性文章.

Node.js模块 - export vs module.exports

NodeJS module.exports的目的是什么,你如何使用它?

掌握节点