来自本人论坛:www.tnodejs.com tnodejs.com
最近大家都说两者是一样的,其实不然,本文来自
http://www.hacksparrow.com/node-js-exports-vs-module-exports.html 翻译exports.name = function() { console.log('My name is Lemmy Kilmister'); };
我们可以通过如下方法执行访问:
var rocker = require('./rocker.js'); rocker.name(); // 'My name is Lemmy Kilmister'那么 module.exports 存在的意义是什么?他是否在编码中也是正确合法的?
module.exports = 'ROCK IT!'; exports.name = function() { console.log('My name is Lemmy Kilmister'); };创建另外一个文件,并且执行:
var rocker = require('./rocker.js'); rocker.name(); // TypeError: Object ROCK IT! has no method 'name'可以看到执行结果中无法获取 name 这个 function 。 rocker.js 中最开始就执行了 module.exports ,根据之前我们介绍的,在 module.exports 执行后他将拒绝所有的 exports 模块,因此我们的 exports.name 将会失效。从而我们无法在 require 模块后获取该方法。
module.exports = function(name, age) { this.name = name; this.age = age; this.about = function() { console.log(this.name +' is '+ this.age +' years old'); }; };and you'd use it this way:
var Rocker = require('./rocker.js'); var r = new Rocker('Ozzy', 62); r.about(); // Ozzy is 62 years oldIn this case, your module is an array:
module.exports = ['Lemmy Kilmister', 'Ozzy Osbourne', 'Ronnie James Dio', 'Steven Tyler', 'Mick Jagger'];and you may use it this way:
var rocker = require('./rocker.js'); console.log('Rockin in heaven: ' + rocker[2]); //Rockin in heaven: Ronnie James DioSo you get the point now - if you want yourmodule to be of a specific object type, use module.exports; if you want yourmodule to be a typical module instance, use exports.
module.exports.name = function() { console.log('My name is Lemmy Kilmister'); };does the same thing as:
exports.name = function() { console.log('My name is Lemmy Kilmister'); };But note that, they are not the same thing.As I said earlier module.exports is the real deal, exports is just its littlehelper. Having said that, exports is the recommended object unless you areplanning to change the object type of your module from the traditional 'module instance'to something else.
var EventEmitter = require('events').EventEmitter; module.exports = new EventEmitter(); // Do some work, and after some time emit // the 'ready' event from the module itself. setTimeout(function() { module.exports.emit('ready'); }, 1000);
var a = require('./a'); a.on('ready', function() { console.log('module a is ready'); });
setTimeout(function() { module.exports = { a: "hello" }; }, 0);
var x = require('./x'); console.log(x.a);