Skip to content

Instantly share code, notes, and snippets.

@mdnmdn
Last active June 1, 2017 06:22
Show Gist options
  • Save mdnmdn/f50c7c17afbc7a925d9db981b5dee70d to your computer and use it in GitHub Desktop.
Save mdnmdn/f50c7c17afbc7a925d9db981b5dee70d to your computer and use it in GitHub Desktop.
total.js autoreloader with debug feature
// ===================================================
// IMPORTANT: only for development
// total.js - web application framework for node.js
// http://www.totaljs.com
// ===================================================
var fs = require('fs');
var options = {};
// options.ip = '127.0.0.1';
// options.port = parseInt(process.argv[2]);
// options.config = { name: 'total.js' };
// options.https = { key: fs.readFileSync('keys/agent2-key.pem'), cert: fs.readFileSync('keys/agent2-cert.pem')};
// options.sleep = 2000;
require('total.js').http('debug', options);
var child_process = require('child_process'),
fs = require('fs');
var script = 'debug-run.js',
debug_port = 40894,
env = {}
child_args = ['--debug=' + debug_port, script],
watched_paths = ['components', 'controllers', 'definitions', 'isomorphic',
'modules', 'resources', 'models', 'source',
'workers', 'packages', 'themes', 'configs',
'startup', script, 'config' , 'private'],
delay = 1000,
debug = false,
base_path = process.cwd() + '/',
running = true,
lastTimeout = null,
proc = null;
var reload = function() {
console.log('reload');
lastTimeout = null;
if(proc){
if(debug) console.log('killing' , proc.pid);
proc.kill('SIGHUP');
proc = null;
} else {
proc = child_process.spawn(process.argv[0], child_args,{stdio: 'inherit', env: env});
if(debug) proc.on('message' , console.log.bind(console,'child.message',arguments));
proc.on('exit' ,function(){
if(debug) console.log('child.exit',arguments);
if (running) lastTimeout = setTimeout(reload,delay);
});
//proc.on('uncaughtException' , console.log.bind(console,'child.onUncaughtException'));
console.log('started' , proc.pid);
}
};
reload();
watched_paths.forEach( path => {
var absolutePath = base_path + path;
if (!fs.existsSync(absolutePath)) return;
fs.watch(absolutePath, {recursive: true, persistent: true}, (ev, fileName) => {
if (lastTimeout) {
clearTimeout(lastTimeout);
} else {
console.log('waiting for reload...');
}
lastTimeout = setTimeout(reload,delay);
});
});
process.on('exit',function(){
running = false;
console.log('process.onExit');
});
process.on('SIGINT',function(){
running = false;
console.log('process.SIGINT');
if (proc) proc.kill();
process.exit(0);
});
process.on('uncaughtException',console.log.bind(console,'process.uncaughtException'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment