node模塊

在node中 一個 .js文件就稱之為一個模塊
使用模塊的好處:
1.提高代碼可維護性
2.多個地方調(diào)用
3.避免函數(shù)名和變量沖突

模塊名字就是一個文件名
例如 hello.js,代碼如下:
.............................................................
var s = 'hello';
function greet (name) {
console.log(s+',' + name+'!')
}
module.exports = greeet;
...............................................................
最后一行語句是,將函數(shù)greet作為模塊的輸出暴露出去,這樣其他模塊就可以使用greet函數(shù)啦
ok!在main.js中使用hello模塊的greet函數(shù):
.................................................................
var greet = require('./hello');
var s = 'liao'
greet(s); // hello , liao
.................................................................
main.js中的greet變量就是hello模塊導(dǎo)出的greet函數(shù)

類似這種加載機制被稱為CommonJS規(guī)范, 在這個規(guī)范下,每一個.js文件都是一個模塊。
一個模塊想要對外暴露變量(函數(shù)也是變量),可以用module.exports = variable; 一個模塊要引用其他模塊暴露的變量,用 var ref = require('module_name'),就可以拿到引用模塊的變量。
注意: module.exports = variable 輸出的變量可以是任意對象、函數(shù)、數(shù)組等

模塊原理:

js語言本身沒有模塊機制保證不同模塊使用相同的變量,nodejs如何實現(xiàn)的呢?

js是一種函數(shù)式編程語言,支持閉包,如果把一段js代碼用一個函數(shù)包裝起來,這段代碼的所有全局 變量就變成了函數(shù)內(nèi)部的局部變量
hello.js代碼是這樣的
.............................................................
var s = 'hello';
var name = 'world';
console.log(s + ' ' + name + '!')
...............................................................
node加載hello.js后,它把代碼包裝成這樣執(zhí)行:
...................................................................
(function(){
var s = 'hello';
var name = 'world';
console.log(s + ' ' + name + '!')
})()
...................................................................
以上就實現(xiàn)了模塊的隔離

如何實現(xiàn)模塊的輸出呢 module.exports?

// 準備module對象
var module = {
  id: 'hello',
  exports: {}
};
var load = function () {
  // 讀取的hello.js代碼:
  function greet (name) {
    console.log('hello', + name + '!'); 
  }
  module.exports = greets;
  return module.exports;
};
var exported = load(module);
// 保存,module
save(module, exported);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容