Nodez Nodez - 1 year ago 90
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
let x = 10
let y = 20
let z = 3


case `/`:

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


case `/page`:

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


res.statusCode = 404
res.end(`Error 404`)

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 Source

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.