Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better hot reload code - nodejs - save data on exit #1

Open
shimondoodkin opened this issue Dec 25, 2011 · 0 comments
Open

better hot reload code - nodejs - save data on exit #1

shimondoodkin opened this issue Dec 25, 2011 · 0 comments

Comments

@shimondoodkin
Copy link
Owner

this is a one-liner for each time reload a file

var f=require.resolve('./functions.js');if(require.cache[f]){if(require.cache[f].exports.unload) require.cache[f].exports.unload();delete require.cache[f];}f=require(f);

also i suggest in this code unload event for a module

var f=require.resolve('./functions.js');
if(require.cache[f])
{
    if(require.cache[f].exports.unload) require.cache[f].exports.unload()
    delete require.cache[f];
}
f=require(f);

in the module

exports.unload=function(cb)
{
 //
 save_data();
 //
 if(cb)cb();
}

// exmple saving code:

var last_saved=new Date();
var last_activity=new Date();
var saveing_data=false;
function save_data()
{
 if(last_activity<=last_saved) return;
 if(saveing_data) return;
 saveing_data=true;
   //actualy save data here  
   console.log("data saved")
   require('fs').writeFileSync(__dirname+'/data.json',"text"+(new Date()));
   ///
 last_saved=new Date();
 saveing_data=false;
}
setInterval(save_data,10000);

in the app:

function handleexit(cb)
{
 var fs=Object.keys(require.cache)
 function loop()
 {
  if(fs.length==0){cb();return;}
  var f=fs.pop();
  if(require.cache[f].exports.unload)
   require.cache[f].exports.unload(loop)
  else
   loop()
 }
 loop();
}


process.on('SIGTERM', function () {
 console.log('Got SIGTERM, will exit in 10 seconds ');
 var num=1;
 var n=setInterval(function(){
  console.log(num)
  num++;
 },1000); 
 var c=setTimeout(function(){
  if(n)clearTimeout(n);
  process.exit(0);
 },10000) 

 handleexit(function(){
  if(c)clearTimeout(c);
  if(n)clearTimeout(n);
  process.exit(0);
 })
});

process.on('SIGINT', function () {
 console.log('Got SIGINT, will exit in 10 seconds ');
 var num=1;
 var n=setInterval(function(){
  console.log(num)
  num++;
 },1000); 
 var c=setTimeout(function(){
  if(n)clearTimeout(n);
  process.exit(0);
 },10000) 

 handleexit(function(){
  if(c)clearTimeout(c);
  if(n)clearTimeout(n);
  process.exit(0);
 })
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant