Node應用由模塊組成,採用CommonJS模塊規範。javascript
根據這個規範,每一個文件就是一個模塊,有本身的做用域。在一個文件裏面定義的變量、函數、類,都是私有的,對其餘文件不可見。html
// example.js var x = 5; var addX = function (value) { return value + x; };
上面代碼中,變量x
和函數addX
,是當前文件example.js
私有的,其餘文件不可見。java
若是想在多個文件分享變量,必須定義爲global
對象的屬性。node
global.warning = true;
上面代碼的warning
變量,能夠被全部文件讀取。固然,這樣寫法是不推薦的。jquery
CommonJS規範規定,每一個模塊內部,module
變量表明當前模塊。這個變量是一個對象,它的exports
屬性(即module.exports
)是對外的接口。加載某個模塊,實際上是加載該模塊的module.exports
屬性。編程
var x = 5; var addX = function (value) { return value + x; }; module.exports.x = x; module.exports.addX = addX;
上面代碼經過module.exports
輸出變量x
和函數addX
。json
require
方法用於加載模塊。數組
var example = require('./example.js'); console.log(example.x); // 5 console.log(example.addX(1)); // 6
require
方法的詳細解釋參見《Require命令》一節。瀏覽器
CommonJS模塊的特色以下。緩存
Node內部提供一個Module
構建函數。全部模塊都是Module
的實例。
function Module(id, parent) { this.id = id; this.exports = {}; this.parent = parent; // ...
每一個模塊內部,都有一個module
對象,表明當前模塊。它有如下屬性。
module.id
模塊的識別符,一般是帶有絕對路徑的模塊文件名。module.filename
模塊的文件名,帶有絕對路徑。module.loaded
返回一個布爾值,表示模塊是否已經完成加載。module.parent
返回一個對象,表示調用該模塊的模塊。module.children
返回一個數組,表示該模塊要用到的其餘模塊。module.exports
表示模塊對外輸出的值。下面是一個示例文件,最後一行輸出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' ] }
若是在命令行下調用某個模塊,好比node something.js
,那麼module.parent
就是undefined
。若是是在腳本之中調用,好比require('./something.js')
,那麼module.parent
就是調用它的模塊。利用這一點,能夠判斷當前模塊是否爲入口腳本。
if (!module.parent) { // ran with `node something.js` app.listen(8088, function() { console.log('app listening on port 8088'); }) } else { // used with `require('/.something.js')` module.exports = app; }
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'); });
爲了方便,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
。
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(); }; });
Node使用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
命令用於加載文件,後綴名默認爲.js
。
var foo = require('foo'); // 等同於 var foo = require('foo.js');
根據參數的不一樣格式,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會依次搜索如下文件。
這樣設計的目的是,使得不一樣的模塊能夠將所依賴的模塊本地化。
(4)若是參數字符串不以「./「或」/「開頭,並且是一個路徑,好比require('example-module/path/to/file')
,則將先找到example-module
的位置,而後再以它爲參數,找到後續路徑。
(5)若是指定的模塊文件沒有發現,Node會嘗試爲文件名添加.js
、.json
、.node
後,再去搜索。.js
件會以文本格式的JavaScript腳本文件解析,.json
文件會以JSON格式的文本文件解析,.node
文件會以編譯後的二進制文件解析。
(6)若是想獲得require
命令加載的確切文件名,使用require.resolve()
方法。
一般,咱們會把相關的文件會放在一個目錄裏面,便於組織。這時,最好爲該目錄設置一個入口文件,讓require
方法能夠經過這個入口文件,加載整個目錄。
在目錄中放置一個package.json
文件,而且將入口文件寫入main
字段。下面是一個例子。
// package.json { "name" : "some-library", "main" : "./lib/some-library.js" }
require
發現參數字符串指向一個目錄之後,會自動查看該目錄的package.json
文件,而後加載main
字段指定的入口文件。若是package.json
文件沒有main
字段,或者根本就沒有package.json
文件,則會加載該目錄下的index.js
文件或index.node
文件。
第一次加載某個模塊時,Node會緩存該模塊。之後再加載該模塊,就直接從緩存取出該模塊的module.exports
屬性。
require('./example.js'); require('./example.js').message = "hello"; require('./example.js').message // "hello"
上面代碼中,連續三次使用require
命令,加載同一個模塊。第二次加載的時候,爲輸出的對象添加了一個message
屬性。可是第三次加載的時候,這個message屬性依然存在,這就證實require
命令並無從新加載模塊文件,而是輸出了緩存。
若是想要屢次執行某個模塊,可讓該模塊輸出一個函數,而後每次require
這個模塊的時候,從新執行一下輸出的函數。
全部緩存的模塊保存在require.cache
之中,若是想刪除模塊的緩存,能夠像下面這樣寫。
// 刪除指定模塊的緩存 delete require.cache[moduleName]; // 刪除全部模塊的緩存 Object.keys(require.cache).forEach(function(key) { delete require.cache[key]; })
注意,緩存是根據絕對路徑識別模塊的,若是一樣的模塊名,可是保存在不一樣的路徑,require
命令仍是會從新加載該模塊。
Node執行一個腳本時,會先查看環境變量NODE_PATH
。它是一組以冒號分隔的絕對路徑。在其餘位置找不到指定模塊時,Node會去這些路徑查找。
能夠將NODE_PATH添加到.bashrc
。
export NODE_PATH="/usr/local/lib/node"
因此,若是遇到複雜的相對路徑,好比下面這樣。
var myModule = require('../../../../lib/myModule');
有兩種解決方法,一是將該文件加入node_modules
目錄,二是修改NODE_PATH
環境變量,package.json
文件能夠採用下面的寫法。
{ "name": "node_path", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "NODE_PATH=lib node index.js" }, "author": "", "license": "ISC" }
NODE_PATH
是歷史遺留下來的一個路徑解決方案,一般不該該使用,而應該使用node_modules
目錄機制。
若是發生模塊的循環加載,即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
屬性,能夠用來判斷模塊是直接執行,仍是被調用執行。
直接執行的時候(node module.js
),require.main
屬性指向模塊自己。
require.main === module // true
調用執行的時候(經過require
加載該腳本執行),上面的表達式返回false。
CommonJS模塊的加載機制是,輸入的是被輸出的值的拷貝。也就是說,一旦輸出一個值,模塊內部的變化就影響不到這個值。請看下面這個例子。
下面是一個模塊文件lib.js
。
// lib.js var counter = 3; function incCounter() { counter++; } module.exports = { counter: counter, incCounter: incCounter, };
上面代碼輸出內部變量counter
和改寫這個變量的內部方法incCounter
。
而後,加載上面的模塊。
// main.js var counter = require('./lib').counter; var incCounter = require('./lib').incCounter; console.log(counter); // 3 incCounter(); console.log(counter); // 3
上面代碼說明,counter
輸出之後,lib.js
模塊內部的變化就影響不到counter
了。
require
命令是CommonJS規範之中,用來加載其餘模塊的命令。它其實不是一個全局命令,而是指向當前模塊的module.require
命令,然後者又調用Node的內部命令Module._load
。
Module._load = function(request, parent, isMain) { // 1. 檢查 Module._cache,是否緩存之中有指定模塊 // 2. 若是緩存之中沒有,就建立一個新的Module實例 // 3. 將它保存到緩存 // 4. 使用 module.load() 加載指定的模塊文件, // 讀取文件內容以後,使用 module.compile() 執行文件代碼 // 5. 若是加載/解析過程報錯,就從緩存刪除該模塊 // 6. 返回該模塊的 module.exports };
上面的第4步,採用module.compile()
執行指定模塊的腳本,邏輯以下。
Module.prototype._compile = function(content, filename) { // 1. 生成一個require函數,指向module.require // 2. 加載其餘輔助方法到require // 3. 將文件內容放到一個函數之中,該函數可調用 require // 4. 執行該函數 };
上面的第1步和第2步,require
函數及其輔助方法主要以下。
require()
: 加載外部模塊require.resolve()
:將模塊名解析到一個絕對路徑require.main
:指向主模塊require.cache
:指向全部緩存的模塊require.extensions
:根據文件的後綴名,調用不一樣的執行函數一旦require
函數準備完畢,整個所要加載的腳本內容,就被放到一個新的函數之中,這樣能夠避免污染全局環境。該函數的參數包括require
、module
、exports
,以及其餘一些參數。
(function (exports, require, module, __filename, __dirname) { // YOUR CODE INJECTED HERE! });
Module._compile
方法是同步執行的,因此Module._load
要等它執行完成,纔會向用戶返回module.exports
的值。