var?http?=?require('http');
http.createServer(function(req,res){
????res.writeHeader(200,?{'Content-Type'?:?'text/html?;?charset=utf-8'})
????if(req.url?!==?'/favicon.ico'){
????????console.time('test');
????????var?c=1,a=2,b=3;????????
????????res.write(show()+''+c);
????????c=a+b;
????????res.write('<br?/>')
????????res.write(c+'<br?/>');
????????console.timeEnd('test');
????????res.end()????????
????}
}).listen(8000)
function?show(){
????var?str='';
????for(var?i=0;i<10000;i++){
????????str+=i*i*i*i+'<br?/>';
????}
????return?str
}
console.log('server?is?running?at?http://127.0.0.1:8000')最后兩行是1和5!書上寫http.ServerResponse對(duì)象實(shí)現(xiàn)了一個(gè) stream.Writable(可寫流)。但是可寫流一般是異步的(如fs寫入流,zlib流,子進(jìn)程的stdin)啊,這樣對(duì)事件驅(qū)動(dòng)的服務(wù)模型正好。現(xiàn)在我測(cè)試出的是res.write同步也就就是說(shuō)要執(zhí)行完這個(gè)回掉才能執(zhí)行事件隊(duì)列里的下一個(gè)回掉?function(req,res)是ruquest事件的回掉,也就是說(shuō)如果應(yīng)對(duì)好幾萬(wàn)個(gè)并發(fā)請(qǐng)求就要執(zhí)行幾萬(wàn)個(gè)function(req,res),哪怕function(req,res)里沒(méi)有cpu密集應(yīng)用積少成多這不是用戶訪問(wèn)就會(huì)有延遲?但是node非常擅長(zhǎng)處理密集io?。渴俏蚁脲e(cuò)了么?
node.js中http.ServerResponse對(duì)象中的write方法為什么是同步的?
winner4265975
2017-05-28 16:05:03