①具有檔案作用域
②具有通訊規則:載入和匯出規則
1.nodejs中的模組系統,具有檔案作用域,也具有通訊規則,使用require方法載入模組,使用exports介面物件匯出模組中的成員
2.載入require
①語法:
var 自定義變數名稱 = require(『模組』)②兩個作用:執行被載入模組中的**,得到載入模組中的exports匯出介面物件
3.匯出exports
①nodejs中的是模組作用域,預設檔案中的所有成員只在當前檔案模組有效
②對於希望可以被其他模組訪問的成員,可以掛載到exports介面物件中
③匯出多個成員(必須在物件中):
//匯出數字
exports.a=123;
//匯出字串
exports.b='hello';
//匯出函式
exports.c=function
()//
匯出物件
④匯出單個成員(拿到的是就是函式、字串等等,而不是乙個物件):
⑤以下情況會覆蓋
⑥也可以這樣來匯出多個成員
⑦原理解釋:exports是moudle.exports的乙個引用,exports和module.exports的區別在於,每個模組都有乙個module物件,module物件中有乙個exports物件,可以把需要匯出的成員都掛載到module.exports介面物件中,也就是『 module.exports.***=*** 』 的方式,但是每次都這樣書寫太麻煩,所以nodejs為了更加方便,同時在每乙個模組提供了乙個成員叫『 exports 』,令『 exports===module.exports 』 結果為『 true 』 ,所以對於 『 module.exports 』的方式完全可以使用『 exports.***=*** 』。當乙個模組需要匯出單個成員時,這個時候必須用『 module.exports=*** 』 使用『exports=*** 』 不管用,因為每個模組最終向外『 return 』 的是 『 module.exports 』,而exports只是module.exports的乙個引用,所以即便為『 exports=*** 』重新賦值,也不會影響『 module.exports 』 ,並且如果重新賦值以後,exports和module.exports之間的引用關係會斷裂。但是有一種賦值方式比較特殊,『 exports=module.exports 』 這個是用來重新建立引用關係的。
4.require方法載入規則
①優先從快取載入:可以避免重複載入,提高載入效率
②判斷模組標識:require(『 模組標識 』)
nodejs中的模組系統
nodejs中的模組語法關鍵字主要是exports module.exports 以及 require,不要和es6的import export搞混了 匯出exports物件後直接新增新成員 exports.area r pi r 2 對module.exports直接複製 module.expor...
nodejs 模組系統
模組系統分為原生系統跟檔案系統,他們的呼叫優先順序為 檔案系統快取區 原生系統 原生系統快取區 檔案系統 1.原生系統 http,path,fs 等 2.載入檔案系統時還可以指定自定義檔案 hello 或者 root node hello 路徑載入 3.mod 非原生系統的檔案系統 node.js ...
nodejs中的模組
nodejs中的模組管理遵循commonjs規範。使用module.exports 可簡寫為exports 匯出模組,使用require來引入模組。例 mymodule.js var myfunction function name module.exports myfunction 也可也成exp...