標籤:
在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模組的使用