Skip to content

Instantly share code, notes, and snippets.

@sifu
Created October 19, 2010 13:49
Show Gist options
  • Save sifu/634212 to your computer and use it in GitHub Desktop.
Save sifu/634212 to your computer and use it in GitHub Desktop.
autoreload a server
depends on http://github.com/mikeal/watch
var watch = require( 'watch' ),
path = require( 'path' ),
spawn = require('child_process').spawn
;
function autoreload( opt ) {
var child = null, ranOnce = false;
function start( ) {
child = spawn( opt.command, opt.args );
child.stdout.on( 'data', function( data ) {
console.info( data.toString( 'utf8' ) );
} );
child.stderr.on( 'data', function( data ) {
console.error( data.toString( 'utf8' ) );
} );
};
function stop( ) {
if( child ) {
child.kill( 'SIGTERM' );
}
};
start( );
watch.watchTree( opt.watch, { ignoreDotFiles: true }, function( f, curr, prev ) {
if( curr ) {
if( ranOnce ) { // ingore first callback
console.info( 'Restarting...' );
stop( );
start( );
} else {
ranOnce = true;
}
}
} );
}
autoreload( {
command: 'node',
args: [ path.join( __dirname, 'server.js' ) ],
watch: __dirname
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment