Skip to content

Instantly share code, notes, and snippets.

@Marak
Created January 13, 2010 13:28
Show Gist options
  • Save Marak/276185 to your computer and use it in GitHub Desktop.
Save Marak/276185 to your computer and use it in GitHub Desktop.
var posix = require('posix'),
debug = require("./debug"),
sys = require('sys');
var application = {};
//location to application state data
application.dataPath = '/var/www/foobar.com/server/data.json';
application.data = {};
// helper function for lazy initing objects
function jset( o,d,t ){
if(typeof eval(o) == 'undefined'){ eval( o + ' = ' + d + ';' ); }
return true;
}
process.addListener("SIGINT", function(){
application.end();
});
application.start = function(){
//load data.json into application state
var x = posix.open(application.dataPath,process.O_CREAT|process.O_WRONLY|process.O_EXCL,0444).addCallback(function(fd){
sys.puts('new datastore created');
});
var boot = posix.cat( application.dataPath ).addCallback(function (applicationState) {
//sys.puts(JSON.stringify(applicationState));
/* try to evaluate application state into memory */
try {
eval( applicationState )
}
catch(err){
debug.log( 'applicationState failed to evaluate : ' + JSON.stringify(err) )
}
// application options
jset( 'application.data.totalRequests' , 0 );
jset( 'application.data.activeRequests' , 0 );
jset( 'application.data.openRequests' , 0 );
application.data.startTime = new Date();
application.data.currentTime = new Date();
application.data.endTime = null; // halting problem >.<
});
};
application.end = function(){
sys.puts('application end');
application.saveState(true);
};
application.saveState = function(shutdown){
sys.puts('application saveState');
//dump data.json into application state
var mode = 0444;
var x = posix.open(application.dataPath ,process.O_RDWR|process.O_TRUNC,0444).addCallback(function(fd){
sys.puts('opening : ' + application.dataPath);
/* open and write */
posix.write( fd, 'application.data = ' + JSON.stringify( application.data ) + ';' ).addCallback(function(){
sys.puts('application state serialized and stored in : ' + application.dataPath);
if(shutdown){process.exit();}
});
});
};
exports.application=application;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment