nodeJS基礎:模組系統

來源:互聯網
上載者:User

標籤: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基礎:模組系統

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.