在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'); // } //寫法2 function 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
//寫法4 module.exports=function(){ console.log('hello world'); }
main.js
var me=require('./hello.js'); me();
module通過module對象可以訪問到當前模塊的一些相關信息,但最多的用途是替換當前模塊的導出對象。
//寫法1 // exports.hello=function(){ // console.log('hello world'); // } //寫法2 function hello(){ console.log('hello world'); } exports.hello=hello; //寫法3 // this.hello=function(){ // console.log('hello world'); // } mordel.exports=function(){ console.log('bad world'); }