CommonJS規范


目錄

概述

CommonJS是服務器模塊的規范,Node.js采用了這個規范。

根據CommonJS規范,一個單獨的文件就是一個模塊。每一個模塊都是一個單獨的作用域,也就是說,在一個文件定義的變量(還包括函數和類),都是私有的,對其他文件是不可見的。

var x = 5; var addX = function(value) { return value + x; }; 

上面代碼中,變量x和函數addX,是當前文件私有的,其他文件不可見。

如果想在多個文件分享變量,必須定義為global對象的屬性。

global.warning = true; 

上面代碼的waining變量,可以被所有文件讀取。當然,這樣寫法是不推薦的。

CommonJS規定,每個文件的對外接口是module.exports對象。這個對象的所有屬性和方法,都可以被其他文件導入。

var x = 5; var addX = function(value) { return value + x; }; module.exports.x = x; module.exports.addX = addX; 

上面代碼通過module.exports對象,定義對外接口,輸出變量x和函數addX。module.exports對象是可以被其他文件導入的,它其實就是文件內部與外部通信的橋梁。

require方法用於在其他文件加載這個接口,具體用法參見《Require命令》的部分。

var example = require('./example.js'); console.log(example.x); // 5 console.log(addX(1)); // 6

module對象

每個模塊都有一個module變量,該變量指向當前模塊。module不是全局變量,而是每個模塊都有的本地變量。

  • module.id 模塊的識別符,通常是帶有絕對路徑的模塊文件名。
  • module.filename 模塊的文件名。
  • module.loaded 返回一個布爾值,表示模塊是否已經完成加載。
  • module.parent 返回一個對象,表示調用該模塊的模塊。
  • module.children 返回一個數組,表示該模塊要用到的其他模塊。

下面是一個示例文件,最后一行輸出module變量。

// example.js var jquery = require('jquery'); exports.$ = jquery; console.log(module); 

執行這個文件,命令行會輸出如下信息。

{ id: '.', exports: { '$': [Function] }, parent: null, filename: '/path/to/example.js', loaded: false, children: [ { id: '/path/to/node_modules/jquery/dist/jquery.js', exports: [Function], parent: [Circular], filename: '/path/to/node_modules/jquery/dist/jquery.js', loaded: true, children: [], paths: [Object] } ], paths: [ '/home/user/deleted/node_modules', '/home/user/node_modules', '/home/node_modules', '/node_modules' ] } 

module.exports屬性

module.exports屬性表示當前模塊對外輸出的接口,其他文件加載該模塊,實際上就是讀取module.exports變量。

var EventEmitter = require('events').EventEmitter; module.exports = new EventEmitter(); setTimeout(function() { module.exports.emit('ready'); }, 1000); 

上面模塊會在加載后1秒后,發出ready事件。其他文件監聽該事件,可以寫成下面這樣。

var a = require('./a'); a.on('ready', function() { console.log('module a is ready'); }); 

exports變量

為了方便,Node為每個模塊提供一個exports變量,指向module.exports。這等同在每個模塊頭部,有一行這樣的命令。

var exports = module.exports;

造成的結果是,在對外輸出模塊接口時,可以向exports對象添加方法。

exports.area = function (r) { return Math.PI * r * r; }; exports.circumference = function (r) { return 2 * Math.PI * r; };

注意,不能直接將exports變量指向一個函數。因為這樣等於切斷了exports與module.exports的聯系。

exports = function (x){ console.log(x);};

上面這樣的寫法是無效的,因為它切斷了exports與module.exports之間的鏈接。

下面的寫法也是無效的。

exports.hello = function() { return 'hello'; }; module.exports = 'Hello world'; 

上面代碼中,hello函數是無法對外輸出的,因為module.exports被重新賦值了。

如果一個模塊的對外接口,就是一個函數或對象時,不能使用exports輸出,只能使用module.exports輸出。

module.exports = function (x){ console.log(x);};

如果你覺得,exports與module.exports之間的區別很難分清,一個簡單的處理方法,就是放棄使用exports,只使用module.exports。

AMD規范與CommonJS規范的兼容性

CommonJS規范加載模塊是同步的,也就是說,只有加載完成,才能執行后面的操作。AMD規范則是非同步加載模塊,允許指定回調函數。由於Node.js主要用於服務器編程,模塊文件一般都已經存在於本地硬盤,所以加載起來比較快,不用考慮非同步加載的方式,所以CommonJS規范比較適用。但是,如果是瀏覽器環境,要從服務器端加載模塊,這時就必須采用非同步模式,因此瀏覽器端一般采用AMD規范。

AMD規范使用define方法定義模塊,下面就是一個例子:

define(['package/lib'], function(lib){ function foo(){ lib.log('hello world!'); } return { foo: foo }; });

AMD規范允許輸出的模塊兼容CommonJS規范,這時define方法需要寫成下面這樣:

define(function (require, exports, module){ var someModule = require("someModule"); var anotherModule = require("anotherModule"); someModule.doTehAwesome(); anotherModule.doMoarAwesome(); exports.asplode = function (){ someModule.doTehAwesome(); anotherModule.doMoarAwesome(); }; });

require命令

基本用法

Node.js使用CommonJS模塊規范,內置的require命令用於加載模塊文件。

require命令的基本功能是,讀入並執行一個JavaScript文件,然后返回該模塊的exports對象。如果沒有發現指定模塊,會報錯。

// example.js var invisible = function () { console.log("invisible"); } exports.message = "hi"; exports.say = function () { console.log(message); } 

運行下面的命令,可以輸出exports對象。

var example = require('./example.js'); example // { // message: "hi", // say: [Function] // } 

如果模塊輸出的是一個函數,那就不能定義在exports對象上面,而要定義在module.exports變量上面。

module.exports = function () { console.log("hello world") } require('./example2.js')() 

上面代碼中,require命令調用自身,等於是執行module.exports,因此會輸出 hello world。

加載規則

require命令接受模塊名作為參數。

(1)如果參數字符串以“/”開頭,則表示加載的是一個位於絕對路徑的模塊文件。比如,require('/home/marco/foo.js')將加載/home/marco/foo.js。

(2)如果參數字符串以“./”開頭,則表示加載的是一個位於相對路徑(跟當前執行腳本的位置相比)的模塊文件。比如,require('./circle')將加載當前腳本同一目錄的circle.js。

(3)如果參數字符串不以“./“或”/“開頭,則表示加載的是一個默認提供的核心模塊(位於Node的系統安裝目錄中),或者一個位於各級node_modules目錄的已安裝模塊(全局安裝或局部安裝)。

舉例來說,腳本/home/user/projects/foo.js執行了require('bar.js')命令,Node會依次搜索以下文件。

  • /home/user/projects/node_modules/bar.js
  • /home/user/node_modules/bar.js
  • /home/node_modules/bar.js
  • /node_modules/bar.js

這樣設計的目的是,使得不同的模塊可以將所依賴的模塊本地化。

(4)如果傳入require方法的是一個目錄,那么require會先查看該目錄的package.json文件,然后加載main字段指定的腳本文件。否則取不到main字段,則會加載index.js文件或index.node文件。

舉例來說,下面是一行普通的require命令語句。

var utils = require( "utils" ); 

Node尋找utils腳本的順序是,首先尋找核心模塊,然后是全局安裝模塊,接着是項目安裝的模塊。

[ '/usr/local/lib/node', '~/.node_modules', './node_modules/utils.js', './node_modules/utils/package.json', './node_modules/utils/index.js' ] 

(5)如果指定的模塊文件沒有發現,Node會嘗試為文件名添加.js、.json、.node后,再去搜索。.js文件會以文本格式的JavaScript腳本文件解析,.json文件會以JSON格式的文本文件解析,.node文件會議編譯后二進制文件解析。

(6)如果想得到require命令加載的確切文件名,使用require.resolve()方法。

模塊的緩存

第一次加載某個模塊時,Node會緩存該模塊。以后再加載該模塊,就直接從緩存取出該模塊的exports屬性。

require('./example.js'); require('./example.js').message = "hello"; require('./example.js').message // "hello" 

上面代碼中,連續三次使用require命令,加載同一個模塊。第二次加載的時候,為輸出的對象添加了一個message屬性。但是第三次加載的時候,這個message屬性依然存在,這就證明require命令並沒有重新加載模塊文件,而是輸出了緩存。

如果想要多次執行某個模塊,可以輸出一個函數,然后多次調用這個函數。

緩存是根據絕對路徑識別模塊的,如果同樣的模塊名,但是保存在不同的路徑,require命令還是會重新加載該模塊。

模塊的循環加載

如果發生模塊的循環加載,即A加載B,B又加載A,則B將加載A的不完整版本。

// a.js exports.x = 'a1'; console.log('a.js ', require('./b.js').x); exports.x = 'a2'; // b.js exports.x = 'b1'; console.log('b.js ', require('./a.js').x); exports.x = 'b2'; // main.js console.log('main.js ', require('./a.js').x); console.log('main.js ', require('./b.js').x); 

上面代碼是三個JavaScript文件。其中,a.js加載了b.js,而b.js又加載a.js。這時,Node返回a.js的不完整版本,所以執行結果如下。

$ node main.js b.js a1 a.js b2 main.js a2 main.js b2 

修改main.js,再次加載a.js和b.js。

// main.js console.log('main.js ', require('./a.js').x); console.log('main.js ', require('./b.js').x); console.log('main.js ', require('./a.js').x); console.log('main.js ', require('./b.js').x); 

執行上面代碼,結果如下。

$ node main.js b.js a1 a.js b2 main.js a2 main.js b2 main.js a2 main.js b2 

上面代碼中,第二次加載a.js和b.js時,會直接從緩存讀取exports屬性,所以a.js和b.js內部的console.log語句都不會執行了。

require.main

正常的腳本調用時,require.main屬性指向模塊本身。

require.main === module // true 

如果是在REPL環境使用require命令,則上面的表達式返回false。

通過require.main屬性,可以獲取模塊的信息。比如,module對象有一個filename屬性(正常情況下等於 __filename),可以通過require.main.filename屬性,得知當前模塊的入口文件。

文章出處:http://javascript.ruanyifeng.com/nodejs/commonjs.html#


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM