I am learning node.js, and I am not managing to find a direct answer to this question. How does node.js deal with HTTP incoming requests, if they come in virtually at the same time? Let's say that one HTTP request comes in at a given time. As a result, the value of a global variable might change. However, at virtually the same time, another request comes in. In order to service the new request, the value of that one global variable is needed, but the code for the first request is still executing. How does node react to this?
1 Answer
Node.js processes the request one after the other. There is only one thread.
However, if you for example query the database for some information and pass a callback, while the query is executed, node.js can process new requests. Once the database query is completed, node.js calls the callback and finishes processing the first request.
EDIT:
Simple server example:
var http = require('http');
var numresponses = 0;
http.createServer(function (request, response) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is response #' + (++numresponses));
}).listen(80);
this server will always print out the number of the request even if two requests happen simultaneously, node will choose one that gets processed first, and both will have different numbers.
3 Comments
user3289157
so, if I wanted to make sure that no race conditions occur, I could send all the requests to a queue and service them one by one, using callbacks to ensure sequential execution, right?
Ferdi265
you don't need to create a queue. Node.js already does that for you. when creating an http webserver with node, the callback passed to the
createServer function will be executed for every request in the queue, which is created by node itself. because node scripts are fundamentally single-threaded, there are no thread-based race-conditions in node.Ferdi265
added simple server example to answer.