在node.js使用underscore.js

Reading time ~2 minutes

太早起床,只好隨便研究點東西 :P
 
underscore.js對javascript來說是一個蠻好用的工具, 在前端應用程式的開發中也很常被利用到,但同樣以javascript為基礎開發的node.js, 能否直接使用underscore.js呢?

嘗試以下面的程式碼用node.js跑:

require('./underscore.js');                                                                

var a = [1, 23, 6, 11, 25, 12, 33, 11, 4];

_.forEach(a, function(v) {
console.log(v);
});


執行結果會得到“ReferenceError: _ is not defined”
打開underscore.js的原始碼一看, 發現了這一段, 其實它是有針對node.js做手腳的:


// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}

也就是, 在browser時, “_"是一個global object, 但在node.js則不是, 原本的範例如果改成這樣就可以了:


var _us = require('./underscore.js');                                                                

var a = [1, 23, 6, 11, 25, 12, 33, 11, 4];

_us.forEach(a, function(v) {
console.log(v);
});


這樣一來, 前後端也可以共用同一份underscore.js了

補充: 類似的工具還有async這個, 也是前後端都可以應用

via Blogger http://bit.ly/R10QWD