在 Node.js 中,不同支 JS 檔案分別撰寫各自的功能,構成數個 module,module 間如果要互相溝通必須依賴特定的指令,基本有以下的方式可以使用:
- require:
匯入其他 JS 檔案的內容使用。
– - module.exports:
匯出內容供其他 JS 檔案取用。
–
require
使用 require 指令可以在當前的 JS 檔案中匯入其他 JS 撰寫的內容來使用,假設目前編輯的檔案為 app.js ,而要從 data.js 匯入資料:
//我是 app.js //從 data.js 匯入資料 var data = require('./data'); //執行匯入的結果 console.log(data);
範例中先宣告一個變數來儲存匯入的內容,require 中接收的是一個路徑,用來指向我們要匯入的檔案,使用 “./” 代表與目前 JS 檔案處於當層,同時 Node.js 會預設判斷匯入的檔案為 JS,所以不必寫副檔名。
module.exports
使用 module.exports 指令來將指定的內容匯出給其他 module 使用,假設目前編輯的檔案為 data.js,匯出內容給其他 JS module 使用:
//我是 data.js var b = 2; //匯出變數 module.exports = b; //匯出物件 module.exports = { title: 'data', number: b };
使用 module.exports 匯出的部份可以供其他 JS module 來使用,它遵循著基本 JS 的規則,可以匯出變數、物件、函數……等。
而匯出的部份還可以使用另外一種寫法,直接使用 exports 指令來匯出指定的部份,例如:
//使用 exports 匯出物件 exports.data = 10; exports.notice = function(){ return 'notice!!'; }; //等於使用 module.exports 匯出 module.exports = { data: 10, notice: function(){ return 'notice!!'; } } //使用 module.exports 會覆蓋單用 exports 的結果 module.exports = { name: 'Mike' };
範例中,首先使用 exports 指令,分別匯出了 data 及 notice,雖然看起來是 2 筆資料,但其實屬於同一個物件,只是分開匯出,他等同於使用 module.exports 去匯出一個物件,而使用 module.exports 後會去覆蓋 exports 的結果,最終輸出 data 和 notice 都不存在了,只剩下一個物件,其屬性 name 值為 Mike。
兩種指令都可以使用,但比較推薦使用 module.exports。