module.exports
object
module.exports 是系统模块创建的,可以用来导出模块里的实例、对象。
创建一个a.js 模块
const EventEmitter = require('events');
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(() => {
module.exports.emit('ready');
}, 1000);
在另一个文件中可以作如下操作
const a = require('./a');
a.on('ready', () => {
console.log('module a is ready');
});
注意 module.exports 赋值必须立即执行,不能在回调函数中赋值。
x.js
setTimeout(() => {
module.exports = { a: 'hello' };
}, 0);
y.js
const x = require('./x');
console.log(x.a);
exports 别名
- 在创建一个模块时,本模块内会创建一个本地变量 exports.
- 初始化为 exports = module.exprots.
function require(...) {
// ...
((module, exports) => {
// Your module code here
exports = some_func; // re-assigns exports, exports is no longer
// a shortcut, and nothing is exported.
module.exports = some_func; // makes your module export 0
})(module, module.exports);
return module;
}
exports 和module.exports
在模块创建后默认的情况下exports == module.exprots.
对exports 、module.exprots任意一个赋值操作, exports != module.exprots
整理后在使用中能清楚掌握其中的关系和使用方法。阅读一下nodejs源码相关部分,有收获再补充