Created
August 14, 2015 17:35
-
-
Save matthias-schuetz/869c7764741f1cedd6de to your computer and use it in GitHub Desktop.
node.js web server with browser reload functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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