module.exports
module.exports
对象由 Module
系统创建。
有时这是不可接受的;许多人希望他们的模块成为某个类的实例。
为此,则将所需的导出对象赋值给 module.exports
。
将所需的对象赋值给 exports
只会重新绑定本地的 exports
变量,这可能不是想要的。
例如,假设正在制作一个名为 a.js
的模块:
const EventEmitter = require('node:events');
module.exports = new EventEmitter();
// 做一些工作,一段时间后从模块本身触发 'ready' 事件。
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);
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.
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');
});
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);