I know that articles and tutorials were not once created on this topic. But still. Why this code can process requests only sequentially despite the fact that it is built using setImmediate:
var http = require('http'), replicate, fileServer; replicate = function (symbol, count) { var str = "", i; for (i = 0; i <= count; i += 1) { str += symbol; } return str; }; fileServer = function (response) { var Klength = 1024, i = 0; response.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': 1024 * Klength }); setImmediate(function f() { for (; i < Klength; i += 1) { response.write(replicate('A', 5)); setImmediate(f); return; } response.end(); }); }; http.createServer(function (request, response) { if (request.url === '/favicon.ico') { response.writeHead(404); response.end(); return; } fileServer(response); }).listen(8000);
The same problem with this implementation:
fileServer = function (response) { var Klength = 1024 * 1024, i = 0, emiter; response.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': Klength }); emiter = new events.EventEmitter(); emiter.addListener('continue', function () { if (i <= Klength) { response.write('A'); i += 1; setImmediate(function () { emiter.emit('continue'); }); return; } response.end(); }); emiter.emit('continue'); };