Skip to content

Instantly share code, notes, and snippets.

@matthias-schuetz
Created August 14, 2015 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matthias-schuetz/869c7764741f1cedd6de to your computer and use it in GitHub Desktop.
Save matthias-schuetz/869c7764741f1cedd6de to your computer and use it in GitHub Desktop.
node.js web server with browser reload functionality
var connect = require('connect');
var serveStatic = require('serve-static');
var http = require('http');
var path = require('path');
var tinylr = require('tiny-lr')();
var chokidar = require('chokidar');
var tinylrPort = 2000;
var httpPort = 3000;
var readline;
var app;
function createApp(watchPath) {
app = connect();
app.use(require('connect-livereload')({
port: tinylrPort,
serverPort: httpPort
}));
app.use(serveStatic(watchPath ? path.resolve(watchPath) : __dirname));
tinylr.listen(tinylrPort);
http.createServer(app).listen(httpPort);
chokidar.watch(watchPath ? path.resolve(watchPath + '/' + '**') : '**', { ignored: /[\/\\]\./ }).on('change', function(filePath) {
tinylr.changed({
body: {
files: [path.resolve(__dirname + '/' + filePath)]
}
});
});
console.log('Server running at http://localhost:' + httpPort);
}
if (process.argv[2]) {
createApp(process.argv[2]);
} else {
readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.question('Enter path or leave blank >> ', function(watchPath) {
createApp(watchPath);
readline.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment