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