【node.js】模組系統、函數

來源:互聯網
上載者:User

標籤: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】模組系統、函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.