在NodeJS中,一般將代碼合理拆分到不同的JS文件中,每一個(gè)文件就是一個(gè)模塊,而文件路徑就是模塊名。每一個(gè)node.js執(zhí)行文件,都自動(dòng)創(chuàng)建一個(gè)module對(duì)象,同時(shí),module對(duì)象會(huì)創(chuàng)建一個(gè)叫exports的屬性,初始化的值是 {},用作文件的導(dǎo)出。
創(chuàng)建一個(gè)main.js,打印moudle
console.log(module);

module
Node為每個(gè)模塊提供一個(gè)exports變量,指向module.exports??梢酝ㄋ椎睦斫鉃椋篹xports和module.exports指向同一個(gè)對(duì)象,及
exports = module.exports = {};。給Module.exports添加屬性類似于給exports添加屬性。例如:
module.exports.name = function() {
console.log('My name is kevin');
};
同樣,exports是這樣的 :
exports.name = function() {
console.log('My name is kevin');
};
module.exports
(1)程序?qū)С龅挠肋h(yuǎn)是 module.exports
(2)如果你創(chuàng)建了 既有 exports 又有 module.exports 的模塊,那它會(huì)返回 module.exports(如下圖)

為什么要拿一個(gè) exports 來(lái)做 module.exports 的引用?而不是直接使用 module.exports ?
其實(shí)是為了保證,模塊的初始化環(huán)境是干凈的。同時(shí)也方便我們,即使改變了 module.exports 指向的對(duì)象后,依然能沿用 exports的特性。通過(guò)
exports = module.exports的方法,讓其恢復(fù)原來(lái)的特點(diǎn)。
使用場(chǎng)景
什么情況下使用module.exports,什么時(shí)候用exports?
如果你想你的模塊是一個(gè)特定的類型就用Module.exports。如果你想的模塊是一個(gè)典型的“實(shí)例化對(duì)象”就用exports;及你的模塊屬于“模塊實(shí)例(module instances)”,就像官方文檔中給出的示例那樣,那么exports足以滿足要求。
最后用官方的一句話,簡(jiǎn)述兩者區(qū)別:
If you want the root of your module’s export to be a function (such as a constructor)
or if you want to export a complete object in one assignment instead of building it one property at a time,
assign it to module.exports instead of exports.