Thread Safety in Node.js July 26, 2011
Probably my last post about Node.js for a while. My original implementation of the webserver used page objects in the following way:
index.html -> /site/pages/index.js
Meaning that when index.html was requested, index.js was located and executed. A side effect of this, using the node.js construct "require", is that the js page will only be loaded once. Which was bad because I had my code structured in the following way:
//index.js:
this.title = "My page title";
this.load = function(..., finishedCallback){
this.title = figureOutDynamicTitle(parameters);
finishedCallback();
}
Granted, when someone went to index.html, there was a very small time that they might get the wrong title, in this example. But for things, like setting an array on the page to the value loaded from the database, or where you might have another case in the load function where the array doesn't get set at all, there's a very good chance that someone will see something that someone else was only supposed to see.
How I fixed this was to pass back the page object to the finishedCallback. The page object was declared, built and passed back all within the context of the load function, so it never has a chance to be wrong! This is how it looks now
//index.js
this.load = function(..., finishedCallback){
var page = { title: figureOutDynamicTitle(parameters) };
finishedCallback({ page: page });
}
This works. And it's super fast still.