Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Node.js server accept incoming requests while the event queue is blocked?

So I'm just starting to dive into Node and I understand that the I/O is non-blocking and that the event loop is blocking but what I am wondering is:

If you have code which is blocking the event queue, will the server still be able to place incoming requests at the end of the queue or will all of them just time out/bounce?

like image 438
Cory Danielson Avatar asked Mar 22 '12 18:03

Cory Danielson


People also ask

Do NodeJS servers block on HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.

What is blocking the event loop?

If a thread is taking a long time to execute a callback (Event Loop) or a task (Worker), we call it "blocked". While a thread is blocked working on behalf of one client, it cannot handle requests from any other clients.

Does NodeJS use multithreading internally to handle incoming requests?

NodeJS server has an internal component referred to as the EventLoop which is an infinite loop that receives requests and processes them. This EventLoop is single threaded.

What is the difference between blocking and non-blocking calls and its relationship with NodeJS?

Blocking refers to operations that block further execution until that operation finishes while non-blocking refers to code that doesn't block execution. Or as Node. js docs puts it, blocking is when the execution of additional JavaScript in the Node. js process must wait until a non-JavaScript operation completes.


1 Answers

Yes. The server is still able to queue up requests. To demonstrate, I made the following file which blocks for 10 seconds, ran it, and curl'd the server on another terminal.

require('http').createServer(function(req, res) {
  console.log('got a request!');
  res.end('hello world!\n');
}).listen(3000);

var t = Date.now();
console.log('blocking..');
while(t + 10000 > Date.now());
console.log('not blocking anymore');

The result from running it

blocking..
not blocking anymore
got a request!
like image 180
fent Avatar answered Oct 01 '22 10:10

fent