一,概述
Node應用由模塊組成,採用CommonJS模塊規範。
根據這個規範,每個文件就是一個模塊,有自己的作用域。在一個文件裏面定義的變量、函數、類,都是私有的,對其他文件不可見。
// example.js
var x = 5;
var addX = function (value) {
return value + x;
};
上面代碼中,變量x
和函數addX
,是當前文件example.js
私有的,其他文件不可見。
如果想在多個文件分享變量,必須定義爲global
對象的屬性。
global.warning = true;
上面代碼的warning
變量,可以被所有文件讀取。當然,這樣寫法是不推薦的。
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
。
require
方法用於加載模塊。
var example = require('./example.js');
console.log(example.x); // 5
console.log(example.addX(1)); // 6
CommonJS模塊的特點如下。
- 所有代碼都運行在模塊作用域,不會污染全局作用域。
- 模塊可以多次加載,但是隻會在第一次加載時運行一次,然後運行結果就被緩存了,以後再加載,就直接讀取緩存結果。要想讓模塊再次運行,必須清除緩存。
- 模塊加載的順序,按照其在代碼中出現的順序。
二,module對象
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;
}
2.1 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');
});
2.2 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
。
三,require命令
3.1 基本用法
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。
3.2 加載規則
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會依次搜索以下文件。
- /usr/local/lib/node/bar.js
- /home/user/projects/node_modules/bar.js
- /home/user/node_modules/bar.js
- /home/node_modules/bar.js
- /node_modules/bar.js
這樣設計的目的是,使得不同的模塊可以將所依賴的模塊本地化。
(4)如果參數字符串不以“./“或”/“開頭,而且是一個路徑,比如require('example-module/path/to/file')
,則將先找到example-module
的位置,然後再以它爲參數,找到後續路徑。
(5)如果指定的模塊文件沒有發現,Node會嘗試爲文件名添加.js
、.json
、.node
後,再去搜索。.js
件會以文本格式的JavaScript腳本文件解析,.json
文件會以JSON格式的文本文件解析,.node
文件會以編譯後的二進制文件解析。
(6)如果想得到require
命令加載的確切文件名,使用require.resolve()
方法。
3.3 目錄的加載規則
通常,我們會把相關的文件會放在一個目錄裏面,便於組織。這時,最好爲該目錄設置一個入口文件,讓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
文件。
3.4 模塊的緩存
第一次加載某個模塊時,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
命令還是會重新加載該模塊。
3.5 環境變量NODE_PATH
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
目錄機制。
3.6 模塊的循環加載
如果發生模塊的循環加載,即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語句都不會執行了。
3.7 require.main
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
了。
4.1 require的內部處理流程
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
的值。
五,參考鏈接
來自《JavaScript 標準參考教程(alpha)》,by 阮一峯