Why express on Node.js processes http requests "serially"? -


i tried below 2 codes. accessed these programs 2 browsers @ same time.

in sample1, res.send executed after processings , general implementation. mean, these "settimeout" can database access or that.

in sample2, res.send executed @ first, , after that, rest of processings happen.

according output of sample1, every http requests processed serially. if people access website @ same time, need wait every prior people. @ first, thought reason because node.js processes serially. noticed it's wrong understanding according result of sample2. result, node.js can simultaneously process bunch of functions include non-blocking code settimeout.

so can't understand why express implemented such way. result, need use cluster pm2 process http request @ same time.

could teach me why express behaves such way? , solution process http requests @ same time using cluster?

sample1

var express = require('express'); var app = express();  app.get('/', function (req, res) {     var id = math.floor(1000*math.random())     console.log('0 - ' + id)     settimeout(()=>{         console.log('1 - ' + id)         settimeout(()=>{             console.log('2 - ' + id)             settimeout(()=>{                 console.log('3 - ' + id)                 res.send('hello world!');             }, 1000)         }, 1000)     }, 1000) });  app.listen(3000, function () {   console.log('example app listening on port 3000!'); }); 

output of sample1

0 - 957 1 - 957 2 - 957 3 - 957 0 - 447 1 - 447 2 - 447 3 - 447 

sample2

var express = require('express'); var app = express();  app.get('/', function (req, res) {     res.send('hello world!');     var id = math.floor(1000*math.random())     console.log('0 - ' + id)     settimeout(()=>{         console.log('1 - ' + id)         settimeout(()=>{             console.log('2 - ' + id)             settimeout(()=>{                 console.log('3 - ' + id)             }, 1000)         }, 1000)     }, 1000) });  app.listen(3000, function () {   console.log('example app listening on port 3000!'); }); 

output of sample2

0 - 902 0 - 742 1 - 902 1 - 742 2 - 902 2 - 742 3 - 902 3 - 742 

it may because of browser described here

i tested sample1 , curl using

for in $(seq 1 5); curl localhost:3000/ & done   

to fire 5 requests , saw them running concurrently - see gif.
not think express serializing requests client.

enter image description here

btw: in output there additional 3rd column showing date.now() each log line initial guess because of buffering log output.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -