模塊是Node.js 應用程式的基本組成部分,檔案和模塊是一一對應的,
一個 Node.js 檔案就是一個模塊,這個檔案可能是JavaScript 代碼、JSON 或者編譯過的C/C++ 擴展,
接下來我們來嘗試創建一個模塊
Node.js 提供了 exports 和 require 兩個物件,其中 exports 是模塊公開的介面,require 用于從外部獲取一個模塊的介面,即所獲取模塊的 exports 物件,
首先創建main.js
//引入了當前目錄下的 cyy.js 檔案(./ 為當前目錄,node.js 默認后綴為 js) var cyy=require("./cyy"); cyy.sing();
接下來創建cyy.js
exports.sing=function(){ console.log("cyy is singing now~"); }
列印結果:

把一個物件封裝到模塊中
那么把cyy.js修改為:
function cyy(){ var name; this.sing=function(song){ console.log("cyy is sing "+song); } this.setName=function(name){ this.name=name; } this.getName=function(){ console.log(this.name); } } module.exports=cyy;
把main.js修改為:
//引入了當前目錄下的 cyy.js 檔案(./ 為當前目錄,node.js 默認后綴為 js) var cyy=require("./cyy"); cyy=new cyy(); cyy.sing("hhh~"); cyy.setName("new cyy"); cyy.getName();
列印結果:

在外部參考該模塊時,其介面物件就是要輸出的cyy物件本身,而不是原先的 exports,
服務器的模塊
模塊內部加載優先級:
1、從檔案模塊的快取中加載
2、從原生模塊加載
3、從檔案中加載
require方法接受以下幾種引數的傳遞:
- http、fs、path等,原生模塊,
- ./mod或../mod,相對路徑的檔案模塊,
- /pathtomodule/mod,絕對路徑的檔案模塊,
- mod,非原生模塊的檔案模塊,
exports 和 module.exports 的使用
如果要對外暴露屬性或方法,就用 exports 就行;
要暴露物件(類似class,包含了很多屬性和方法),就用 module.exports,
不建議同時使用 exports 和 module.exports,
如果先使用 exports 對外暴露屬性或方法,再使用 module.exports 暴露物件,會使得 exports 上暴露的屬性或者方法失效,
原因在于,exports 僅僅是 module.exports 的一個參考,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/143530.html
標籤:JavaScript
下一篇:Node.js 函式
