標籤:com 訪問 引入 相互 color 目錄 rip 對象 blog
為了讓Node.js的檔案可以相互調用,Node.js提供了一個簡單的模組系統。
一個 Node.js 檔案就是一個模組,這個檔案可能是JavaScript 代碼、JSON 或者編譯過的C/C++ 擴充。
建立模組
在 Node.js 中,建立一個模組非常簡單,如下我們建立一個 ‘hello.js‘ 檔案,代碼如下:
var hello = require(‘./hello‘);hello.world();
以上執行個體中,代碼 require(‘./hello‘) 引入了目前的目錄下的hello.js檔案(./ 為目前的目錄,node.js預設尾碼為js)。
Node.js 提供了exports 和 require 兩個對象,其中 exports 是模組公開的介面,require 用於從外部擷取一個模組的介面,即所擷取模組的 exports 對象。
接下來我們就來建立hello.js檔案,代碼如下:
exports.world = function() { console.log(‘Hello World‘);}
在以上樣本中,hello.js 通過 exports 對象把 world 作為模組的提供者,在 main.js 中通過 require(‘./hello‘) 載入這個模組,然後就可以直接訪 問 hello.js 中 exports 對象的成員函數了。
有時候我們只是想把一個對象封裝到模組中,格式如下:
module.exports = function() { // ...}
例如:
//hello.js function Hello() { var name; this.setName = function(thyName) { name = thyName; }; this.sayHello = function() { console.log(‘Hello ‘ + name); }; }; module.exports = Hello;
這樣就可以直接獲得這個對象了:
//main.js var Hello = require(‘./hello‘); hello = new Hello(); hello.setName(‘BYVoid‘); hello.sayHello();
服務端的模組放在哪裡
Node.js中內建了一個叫做"http"的模組,我們在我們的代碼中請求它並把傳回值賦給一個本地變數。
這把我們的本地變數變成了一個擁有所有 http 模組所提供的公用方法的對象。
var http = require("http");...http.createServer(...);
Node.js 的 require方法中的檔案尋找策略如下:
【node.js】模組系統、函數