Please feel free to sort me out if this is a redundant question. (I have searched as much as I can bear before asking)
I am desperately trying to understand the life cycle of the request/response objects.
Consider the following skeleton code:
app.get('/', function(req, res) {
var setCookie = function(err, idCookie) { //callback after cookieSearch in DB
// ... do something with the result of findCookieInDatabase() (handle error, etc.);
res.sendfile('index.html');
}
var cookie = parseCookie(req.get('Cookie')); //parse and format cookie
findCookieInDatabase(cookie, afterCookieSearch); //tries to find cookie is DB
// .. do some content return stuff, etc.
}
(Please note that the original code does a whole lot more, such as checking if 'Cookie' even exists etc.)
I uderstand that req and res objects are created and must be at some point garbage collected. (One would hope)
When findCookieInDatabase() is called with setCookie as a parameter I'm assuming that setCookie is just a string (containing the function) at the time and does not get parsed nor executed until the callback(setCookie) statement is encountered in findCookieInDatabase().
I also understand that I might be utterly wrong with the above assumption which would be due to my lack of understanding the guts of javascript callbacks. (I have searched a lot on this also but all I could find is endless tuts on how to use callbacks. Nothing on what's under the hood)
So the question is this: How does javascript (or node.js) know how long to keep 'res' alive and when is it ok to garbage collect it?
Does the line res.sendfile in setCookie actually act as an active reference because it is invoked through findCookieInDatabase()?
Does javascript actually keep track of all the references and keeps req and/or res alive so long as any part of any called/callback-ed/things are alive?
Any help greatly appreciated. Thanks for reading.