module.exports


module.exports 对象是由 Module 系统创建的。有时候这是不可接受的;很多人希望他们的模块是某个类的实例。要实现这一点,可以将所需的导出对象赋值给 module.exports。将所需对象赋值给 exports 只会重新绑定本地 exports 变量,这可能不是所希望的效果。

【The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to module.exports. Assigning the desired object to exports will simply rebind the local exports variable, which is probably not what is desired.】

例如,假设我们正在制作一个名为 a.js 的模块:

【For example, suppose we were making a module called a.js:】

const EventEmitter = require('node: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); 

然后在另一个文件中可以这样做:

【Then in another file we could do:】

const a = require('./a');
a.on('ready', () => {
  console.log('module "a" is ready');
}); 

module.exports 的赋值必须立即完成。不能在任何回调中进行。这样做是行不通的:

【Assignment to module.exports must be done immediately. It cannot be done in any callbacks. This does not work:】

x.js:

setTimeout(() => {
  module.exports = { a: 'hello' };
}, 0); 

y.js

const x = require('./x');
console.log(x.a);