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')
The last two lines are 1 and 5!
It is written in the book that the http.ServerResponse object implements a stream.Writable (writable stream). However, writable streams are generally asynchronous (such as fs write stream, zlib stream, stdin of subprocess), which is perfect for the event-driven service model. Now what I tested is res.write synchronization, which means that this callback must be executed before the next callback in the event queue can be executed?
function(req,res) is the callback of the ruquest event, which means that if you deal with tens of thousands of concurrent requests, you will need to execute tens of thousands of function(req,res), even if there is no cpu in function(req,res) Intensive applications add up and add up. Doesn’t this mean there will be delays in user access? But node is very good at handling intensive io? Did I think wrong?
I made this show function intentionally, because js is single-threaded and is not good at handling cpu-intensive business, so res.write(show() '' c) takes a longer time and looks better. Is res.write asynchronous? If If res.write is asynchronous, then c=a b will be executed first; then c must be 5;
伊谢尔伦2017-05-31 10:40:35
The advantage of node is that it can handle high concurrency and can handle a large number of requests, but the operations of handling response.write or querying the database are handled by another thread, just like a restaurant, with a chef and a waiter ( Single thread), unlike the general web service framework that only has one chef and a part-time waiter,
So your situation above is not intensive IO, but like, the chef in the restaurant is too busy to handle your dishes, causing the waiter to serve the dishes slowly .
滿天的星座2017-05-31 10:40:35
Obviously, when executing show()
, execution of write()
has not yet started, so your test method itself is wrong.
滿天的星座2017-05-31 10:40:35
write
just writes the data to the internal buffer and then returns. It does not mean that it returns after the data is sent, so it takes up almost no CPU time