Node.js requests VS PHP requests

node.js

I've written in PHP before and when a user connected they get an individual instance of the code which is then closed when the code has finished executing.

In node, I set up my first server to console.log("hi") on every request.
When I refreshed I didn't expect the "hi" to be logged again, but it was – I get its being logged twice because of the browser looking for a favicon.

Is this one of the ways in which node behaves differently to languages like PHP?
Does every user connecting to the server share this – what should I call it – instance, at once? If I set var IP = *users IP* would it be over-written by the next user?

Edit: Is this actually a different instance, but the console doesn't indicate this and prints it straight below? — I added an "I" counter and incremented it on every request and the logged value for I increased, so it must be the same instance.

Best Answer

PHP is a programming language. You use a web-server like Apache to handle HTTP requests and depending to your settings your web-server runs PHP in the background.

Node.js is an environment to run JavaScript. JavaScript is the programming language that you are building your stuff on it. Here Node.js is your web-server that handles HTTP requests.

Node.js doesn't create a new process to handle each request; That's why you see all the outputs in one place. It loads your file once and then serves all users with the same code.

In PHP, a fresh copy of file (either from cache or disk) will be used to serve each request which means re-initialising everything, including your variables, etc.

In JavaScript, this code will only hold the last value assigned to it:

var ip = req.ip;

// or...

function setIP ( ip ) {
    this.ip = ip;
};

setIP( req.ip );

If you want to keep the IP address of each individual users, you should do it either like this:

function User ( ip ) {
    this.ip = ip;
};

var user = new User( req.ip );

Or:

function User ( ip ) {
    var ip = ip;
}

var user = User( req.ip );

You should create a new User instance every time you handle a new request. It can't be one global variable/object, or the value will be replaced anytime you handle a new request.

(These are just example snippets to demonstrate the point)

Related Topic