I don’t think I quite understand how exports work in Node.js. In a bit of sample code, I noticed the exports object used in this manner:
exports = mongoose = require('mongoose')
mongoose.connect(config.db.uri)
exports = Schema = mongoose.Schema
What is happening behind the scenes when you use exports = twice like that? Looks to me like “mongoose” should not be exported. I did this quick test:
var foo
, bar
exports = foo = 'foo'
exports = bar = 'bar'
// reports 'bar' only
console.log(exports)
and the second test does overwrite the first export.
My guess is the original author of that sample code is confused about
module.exportsvsexports. To use theexportsobject, you must add properties to it like this:If you re-assign the
exportsvariable to a new object, you basically lose access to the global exports object that node.js provided for you. If you do this twice or three or N times, the effect is the same. It’s useless. For example: mod_b.jsAnd in mod_a.js
Run
node mod_a.jsand you get:Notice
heightis there butweightis not. Now, what you can do is assignmodule.exportsto be an object, and that is the object that will be returned when another modulerequires your module. So you will see things like.Which will do what you expect. Here’s some informative articles on the details.
Node.js Module – exports vs module.exports
What is the purpose of NodeJS module.exports and how do you use it?
Mastering Node