简体   繁体   中英

How does node.js handle simultaneous http requests?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM