I have been tinkering on NodeJS for a while now. I still don't seem to understand how Node actually runs. Maybe it's just that I can't shed off the PHP mindset. I know it's pretty different from PHP, but still I can't grasp the idea - especially when they keep repeating the terms event-loop, event-driven and REPL.
Does the code run "forever" when it gets started? Is it like a big 'ol browser window in the back-end that the all the clients look at and which listens to some sort of onRequest event from them?
Or is every request an isolated sandbox? Where the code runs for every request, separated from the other requests?
I've seen demos of socket connection chat in the videos, and it seems like it runs like the first point describes. But wouldn't that be "wierd" where all people access the same "space"?
Does the code run "forever" when it gets started? Is it like a big 'ol browser window in the back-end that the all the clients look at and which listens to some sort of onRequest event from them?
What do you refer to as the 'code' ? Once you start a http server, by calling the listen function, yes it runs forever, until you kill the process.
Or is every request an isolated sandbox? Where the code runs for every request, separated from the other requests?
Every incoming request (HttpGet, HttpPost) is handled in a function. For the sake of simplicity I won't use the term callback. This function is a non-blocking asynchronous function. In Javascript, all functions are sort of isolated sandboxes, yet they have access to global variables.
http.createServer(onRequest).listen(80);
var xvz;
function onRequest() {
var abc;
}
In the above code snippet, abc is in an isolated sandbox. However, abc can still access xyz.
The resulting program, of your code, is persistent. Just as you describe it is as if it was a big old browser window, receiving requests and replying to them.
Read the following example.
var http = request("http");
var shared = 1;
function procreq (req, res)
{
var notshared = 1;
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(String(shared++) + ', ' + String(notshared++));
}
var server = http.createServer(procreq);
server.listen(8080);
By running that server example you can see how the program is persistent and the shared
variable is visible for all requests, it is a real server-shared variable. I think, if I recall correctly, that in PHP you can achieve this with memcached (or is it APC?).