標籤:var port 函數 color nod log param ring 擴充
1. node JS 模組介紹
為了讓Node.js的檔案可以相互調用,Node.js提供了一個簡單的模組系統。
模組是Node.js 應用程式的基本組成部分,檔案和模組是一一對應的。換言之,一個 Node.js 檔案就是一個模組,這個檔案可能是JavaScript 代碼、JSON 或者編譯過的C/C++ 擴充。
2. 建立模組
Node.js 提供了exports 和 require 兩個對象,其中 exports 是模組公開的介面,require 用於從外部擷取一個模組的介面,即所擷取模組的 exports 對象。
執行個體:備忘,在以下執行個體中 main.js 與 hello.js 都是處於同一檔案夾下
// main.js// 1. require(‘./hello‘) 引入了目前的目錄下的hello.js檔案(./ 為目前的目錄,node.js預設尾碼為js)。var hello = require("./hello");//2. 使用模組hello.hello("gaoxiong")
// hello.js// 寫法1module.exports.hello = function(name){ console.log(name);};// 寫法2exports.hello = function(name){ console.log(name);}// 寫法1,2都是可以的
在終端執行:node main.js 會列印 gaoxiong,不知道你有沒有留意上面,在調用模組方法時時通過 hello.hello(params);這是為什麼呢?我們在hello.js中 暴露出的不是一個函數嗎?錯了!!!實際上這就牽扯到了以下暴露方法的區別
- exports:只能暴露出一個對象,不管你暴露出什麼,它返回的總是一個對象,對象中包含你所要暴露的資訊
- module.exports能暴露出任意資料類型
驗證:
//第一種情況
// main.jsvar hello = require("./hello");console.log(hello);// hello.jsexports.string = "fdfffd";conosle.log 結果: { string: ‘fdfffd‘ }
// main.jsvar hello = require("./hello");console.log(hello);// hello.jsmodule.exports.string = "fdfffd";// console.log()結果{ string: ‘fdfffd‘}
// main.jsvar hello = require("./hello");console.log(hello);// hello.jsmodule.exports = "fdfffd";//conosle.log() 結果fdfffd
// main.jsvar hello = require("./hello");console.log(hello);// hello.jsexports = "fdfffd"; // conosle.log()結果 => 一個Null 物件{}
對象上面四個情況可以得出:
module.exports.[name] = [xxx] 與 exports.[name] 都是返回一個對象 對象中有 name 屬性
而module.exports = [xxx] 返回實際的資料類型 而 exports = [xxx] 返回一個Null 物件:不起作用的Null 物件
nodeJS基礎:模組系統