javascript - Why is this node.js code blocking? -


i tried play bit node.js , wrote following code (it doesn't make sense, not matter):

var http = require("http"),     sys  = require("sys");  sys.puts("starting...");  var gres = null; var cnt = 0;  var srv = http.createserver(function(req, res){     res.writeheader(200, {"content-type": "text/plain"});     gres = res;     settimeout(output,1000);     cnt = 0; }).listen(81);  function output(){     gres.write("hello world!");     cnt++;     if(cnt < 10)         settimeout(output,1000);     else         gres.end(); } 

i know there bad things in (like using gres globally), question is, why code blocking second request until first completed?

if open url starts writing "hello world" 10 times. if open simultaneous in second tab, 1 tab waits connecting until other tab finished writing "hello world" ten times.

i found nothing explain behaviour.

surely it's overwriting of gres , cnt variables being used first request that's doing it?

[edit actually, chrome won't send 2 @ once, shadow wizard said, code is broken because each new request reset counter, , outstanding requests never closed].

instead of using global, wrap output function closure within createserver callback. it'll have access local res variable @ times.

this code works me:

var http = require("http"),     sys  = require("sys");  sys.puts("starting...");  var srv = http.createserver(function(req, res){     res.writeheader(200, {"content-type": "text/plain"});      var cnt = 0;      var output = function() {         res.write("hello world!\n");         if (++cnt < 10) {             settimeout(output,1000);         } else {             res.end();         }     };      output();  }).listen(81); 

note browser won't render until connection has closed because relevant headers tell display it's downloading aren't there. tested above using telnet.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

php - How can I edit my code to echo the data of child's element where my search term was found in, in XMLReader? -