NodeJS模組的使用

來源:互聯網
上載者:User

標籤:

在NodeJS中,每個js檔案就是一個模組,而檔案路徑就是模組名, 在編寫每個模組時,都有require、exports、module三個預先定義好的變數可供使用。

 

require函數用於在當前模組中載入和使用別的模組,其中js副檔名可省略,require多次不會重複初始化,如果傳遞給require函數的是NodeJS內建模組名稱,不做路徑解析,require(‘express‘);

exports對象是當前模組的匯出對象,用於匯出模組公有方法和屬性。別的模組通過require函數使用當前模組時得到的就是當前模組的exports對象。

匯入匯出結合使用:

hello.js

//寫法1// exports.hello=function(){//     console.log(‘hello world‘);// }//寫法2function hello(){    console.log(‘hello world‘);}exports.hello=hello;//寫法3// this.hello=function(){//     console.log(‘hello world‘);// }

test.js

var me=require(‘./hello.js‘);me.hello();

 還有一種寫法:

hello.js

//寫法4module.exports=function(){    console.log(‘hello world‘);}

main.js

var me=require(‘./hello.js‘);me();

 

module通過module對象可以訪問到當前模組的一些相關資訊,但最多的用途是替換當前模組的匯出對象。

//寫法1// exports.hello=function(){//     console.log(‘hello world‘);// }//寫法2function hello(){    console.log(‘hello world‘);}exports.hello=hello;//寫法3// this.hello=function(){//     console.log(‘hello world‘);// }mordel.exports=function(){    console.log(‘bad world‘);}

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.