讀書筆記: 深入淺出node.js

來源:互聯網
上載者:User

標籤:http   java   使用   檔案   資料   os   


>> 深入淺出node.js

node.js是c++編寫的js運行環境

 

瀏覽器: 渲染引擎 + js引擎

後端的js運行環境

node.js用google v8引擎,同時提供很多系統級的API(檔案操作 網路編程...)

node.js採用事件驅動 非同步編程,為網路服務而設計

瀏覽器端的js有各種安全限制

node.js提供的多數API都是基於事件的,非同步風格。

node.js的優點:充分利用系統資源,執行代碼不會被阻塞以等待某個操作的完成;這個設計非常適合後端的網路服務編程。通過事件註冊,回調,可以提高資源的利用率,改善效能。

為方便伺服器開發,node.js的網路模組有很多:
HTTP, HTTPS, DNS, NET, UDP, TLS等,有助於快速構建web伺服器。

node.js的特點:事件驅動,非同步編程,單進程,單線程。
node.js內部通過單線程高效率地維護事件迴圈隊列,沒有太多的資源佔用和環境切換。

單核效能出色的node.js如何利用多核CPU呢?建議運行多個node.js進程,用某種通訊協定協調各項任務。

javascript的匿名函數和閉包特性非常適合事件驅動,非同步編程。

node.js最擅長的事情是與其他服務通訊。因為node.js是基於事件的無阻塞的,所以非常適合處理並發請求;缺點:node.js是相對新的一個開源項目,所以不太穩定,一直的變,而且缺少足夠多的第三方庫支援。

知名項目託管網站GitHub也嘗試了node應用(NodeLoad). 使用node.js的項目還有MyFox

Node庫socket.io

>> node.js的安裝和配置
window版已經編譯好的node.js安裝包 nodejs.msi,安裝後在Node命令列環境輸入 node -v,有版本號碼輸出,則說明安裝好了。

NPM(Node Package Manager)NodeJs的包管理器。通過NPM我們可以安裝Nodejs的第三方庫。

Unix/Linux安裝NPM:
curl http://npmjs.org/install.sh | sudo sh
擷取shell指令碼,交給sh命令以sudo許可權執行。
安裝完之後 輸入 npm 斷行符號,如輸出協助資訊 則表明安裝成功。

用NPM安裝第三方庫:如underscore
npm install underscore
由於一些特殊的網路環境用npm安裝第三方庫時,容易卡死;可以通過一個鏡像的npm資產庫來安裝,如:
npm --registry "http://npm.hacknodejs.com/" install underscore

設定為預設npm資產庫:
npm config set registry "http://npm.hacknodejs.com" , 設定之後就可以直接 npm install underscore

window下安裝NPM:
下載較新的nodejs.msi(v0.10...)安裝包並安裝後,npm預設也安裝了。

 

命令列下輸入 npm斷行符號即可查看npm的協助資訊。

 


--------------------------------------------------------
node.js中的js模組檔案和script標籤載入的js檔案的區別:node.js的模組檔案中聲明的變數是在閉包內的,不會汙染全域環境,需要被外部調用的介面都掛在exports上。

>> node.js的事件機制
node.js的特點:Evented I/O for V8 javascript (基於V8引擎的事件驅動I/O)

Event模組(events.EventEmitter)是一個簡單的事件監聽器模式的實現。具有方法:
addListener/on, once, removeListener, removeAllListeners, emit...

node.js的事件與前端Dom樹上的事件不同, 不存在冒泡和逐層捕獲等行為,自然也沒有 preventDefault(), stopPropagation(), stopImmediatePropagation()等處理事件傳遞的方法

事件接聽程式模式也是一種事件鉤子(hook)機制,利用事件鉤子匯出內部資料和狀態給外部調用者。


var options = {
host: ‘www.google.com‘,
port: 80,
path: ‘/upload‘,
method: ‘POST‘
};

var req = http.request(options, function(res){
console.log(‘STATUS: ‘ + res.statusCode);
console.log(‘HEADERS: ‘ + JSON.stringfy(res.headers));

res.setEncoding(‘utf8‘);
res.on(‘data‘, function(chunk){
console.log(‘BODY:‘ + chunk);
});

});

req.on(‘error‘, function(e){
console.log(‘problem with request: ‘ + e.message);
});

//write data to request body
req.write(‘data\n‘);
req.write(‘data2\n‘);
req.end();

註:如對於一個事件添加超過10個監聽器,會得到一條警告,因為設計者認為接聽程式太多,可能導致記憶體流失。調用這個語句可以取消10個接聽程式的限制: emitter.setMaxListener(0);

若運行時的錯誤觸發了error事件,會交給error接聽程式處理,若沒有設定error接聽程式,則拋出異常,若異常沒有被捕獲,將會引起退出。

> 如何繼承event.EventEmitter類,如node.js中流對象繼承EventEmitter類:
//類式繼承
function Stream(){
event.EventEmitter.call(this);
}
util.inherits(Stream, event.EventEmitter);

//util.inherits應該是如下這樣實現原型鏈的
util.inherits = function(subClass, superClass){
function F(){}
F.prototype = superClass.prototype;
subClass.prototype = new F;
subClass.prototype.constructor = subClass;
}

> 多事件之間的協作
在大應用中,資料來源和web伺服器分離是必然的。好處有:相同資料來源開發各種豐富的用戶端程式,從多個資料來源拉取資料,渲染到用戶端。
node.js擅長同時並行發起對多個資料來源的請求。
並行請求:
api.getUser(‘username‘, function(profile){
// got the profile
});

api.getTimeline(‘username‘, function(timeline){
// got the timeline
});

api.getSkin(‘username‘, function(skin){
// got the skin
});

這裡存在一個問題:請求可以並行發出,但是如何控制回呼函數的執行順序?

若改為這樣:
api.getUser(‘username‘, function(profile){
api.getTimeline(‘username‘, function(timeline){
api.getSkin(‘username‘, function(skin){
// todo
});
});
});

這將導致請求不能並行發出。

node.js沒有原生支援多事件之間協調的方法,需要藉助第三方庫。如:

var proxy = new EventProxy();
//all方法作用:偵聽完事件後,執行回調,並將偵聽接收到的參數傳入回調中
proxy.all(‘profile‘, ‘timeline‘, ‘skin‘, function(profile, timeline, skin){
//todo
});

api.getUser(‘username‘, function(profile){
proxy.emit(‘profile‘, profile); //觸發事件profile,並傳入實參profile
});

api.getTimeline(‘username‘, function(timeline){
proxy.emit(‘timeline‘, timeline);
});

api.getSkin(‘username‘, function(skin){
proxy.emit(‘skin‘, skin);
});

解決多事件協作的另一種方案:Jscex(代碼可以用同步的思維去寫,非同步方式執行)
如:
var data = $await(Task.whenAll({
profile: api.getUser(‘username‘),
timeline: api.getTimeline(‘username‘),
skin: api.getSkin(‘username‘)
}));

//使用:data.profile, data.timeline, data.skin
// todo

> 利用事件隊列解決雪崩問題
雪崩問題:指在緩衝失效的情景下,大量的並發訪問同時湧入資料庫查詢,資料庫無法承受,進而導致網站整體很慢。

看看加一個狀態鎖的解決方案:
var status = ‘ready‘;
var select = function(callback){
if(status ===‘ready‘){
status = ‘pending‘; //上鎖
db.select(‘SQL‘, function(results){
callback(result);
status = ‘ready‘; //解鎖
});
}
}

連續多次調用select方法時,鎖定期間有的select會不被處理;所以應該用事件隊列的方式來解決。

var proxy = new EventProxy();
var status = ‘ready‘;
var select = function(callback){
proxy.once(‘selected‘, callback);//將所有請求的回調都壓入事件隊列中
if(status === ‘ready‘){
status = ‘pending‘;
db.select(‘SQL‘, function(result){
proxy.emit(‘selected‘, result);
status = ‘ready‘;
});
}
}

>> node.js的非同步I/O實現
同步:程式中的後續任務都需要等待I/O的完成,等待的過程中無法充分利用CPU。
實現I/O並行,充分利用CPU的方式有2種:多線程但進程, 單線程多進程

getFile(‘file_path‘); //耗時m
getFileFromNet(‘url‘); //耗時n
同步I/O的話,需要m+n, 非同步I/O的話,需要max(m,n)
非同步I/O在分布式的環境中很重要,能明顯改善效能。

> 非同步I/O與輪詢技術
進行非阻塞的I/O操作時,要讀取到完整資料,應用程式要多次輪詢,才能確保資料讀取完成,然後進行下一步。輪詢技術的缺點是應用程式主動多次調用,佔用較多CPU時間片。

>> node.js的非同步I/O模型
fs.open = function(path, flags, mode, callback){
callback = arguments[arguments.length - 1];
if( (typeof callback) !== ‘function‘ ){
callback = noop;
}

mode = modeNum(mode, 438); /* 438 = 0666 */
binding.open(pathModule._makeLong(path), stringToFlags(flags), mode, callback);
}

>> string buffer

var fs = require(‘fs‘);
var rs = fs.createReadStream(‘testdata.md‘);
var data = ‘‘;
rs.on(‘data‘, function(trunk){
data += trunk; //trunk 是一個buffer對象
});

rs.on(‘end‘, function(){
console.log(data);
});

npm install bufferhelper;
bufferconcate.js:
var http = require(‘http‘);
var BufferHelper = require(‘bufferhelper‘);
http.createServer(function(req, res){
var bufferHelper = new BufferHelper();
req.on(‘data‘, function(chunk){
bufferHelper.concat(chunk);
});

req.on(‘end‘, function(){
var html = bufferHelper.toBuffer().toString();
res.writeHead(200);
res.end(html);
});
});

 

>> connect模組(node.js web架構)
中介軟體的串流

var app = connect();

//middleware
app.use(connect.staticCache());
app.use(connect.static(__diranme + ‘/public‘) );
app.use(connect.cookieParser());
app.use(connect.session());
...
app.use(function(req, res, next){
//中介軟體
});

app.listen(3001);

connect用use方法註冊中介軟體到中介軟體隊列中。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.