Nodez Nodez - 4 months ago 14
HTTP Question

Confused about Node order rules (synchronous/asynchronous)

My example is a simple HTTP server:

http.createServer((req, res) => {
if(req.method === `GET`){

if(req.headers.cookie === undefined){
let x = 1
let y = 2
let z = 30
}
else{
let x = 10
let y = 20
let z = 3
}

switch(req.url){

case `/`:

// >>>> I need the appropriate variables here for the same client <<<<

break

case `/page`:

// >>>> or here <<<<

break

default:
res.statusCode = 404
res.end(`Error 404`)
}
}
}).listen(3000)


When a client connects, the variables are defined by whether or not the client has a cookie. But what if multiple clients connect at almost the same time? How does Node handle that?

Is it possible for the clients to get mixed up variables, because the if/else statement happens before the switch? Should I instead place 2 copies of the switch in each of the if/else parts?

Or is there no difference?

Answer

Each connection will be it's own "stack" in Node, so they will be independent. Really, each connection will have it's own copy/instance of the req object, and the code you write is only working on that req object. All other req objects that exist are their own stack.

The code will happen in order, so you are safe to have the if/else before the switch.