Created
May 30, 2019 14:09
-
-
Save NoTimeForHero/679032cdf5741b45c9584e102a676aba to your computer and use it in GitHub Desktop.
Simple Hot-Reload server
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
const hotReload = (address, options = {}) => { | |
// Константы | |
const CONST_RELOAD_MESSAGE = 'HOT_RELOAD_NOW'; | |
// Настройки | |
const reconnect_timeout = options.reconnect_timeout || 500; | |
const reconnect_tries = options.reconnect_tries || 5; | |
// Локальные переменные | |
let socket = null; | |
let current_tries = 0; | |
onOpen = () => { | |
current_tries = 0; | |
options.callback('CONNECTED'); | |
}; | |
onClose = () => { | |
if (current_tries > reconnect_tries) { | |
if (options.callback != null) options.callback('ERROR'); | |
return; | |
} | |
if (options.callback != null) options.callback('WARNING'); | |
setTimeout(() => { | |
initSocket(); | |
current_tries++; | |
}, reconnect_timeout); | |
}; | |
onMessage = event => { | |
const message = event.data; | |
if (message === CONST_RELOAD_MESSAGE) { | |
socket.close(); | |
document.location.reload(); | |
} | |
}; | |
initSocket = () => { | |
socket = new WebSocket(address); | |
socket.onopen = onOpen; | |
socket.onclose = onClose; | |
socket.onmessage = onMessage; | |
} | |
initSocket(); | |
} | |
module.exports = hotReload; |
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
'use strict'; | |
const watch = require('watch'); | |
const express = require('express'); | |
const app = express(); | |
const expressWs = require('express-ws')(app); | |
const public_dir = path.join(__dirname, '/public'); | |
app.use(express.static(public_dir)); | |
// Механизм горячей перезагрузки на клиенте при изменении любого HTML файла | |
app.ws('/hot-reload', _ => {}); | |
const wsClients = expressWs.getWss().clients; | |
watch.watchTree(public_dir, {interval: 0.5}, (f) => { | |
if (typeof f !== 'string') return; | |
wsClients.forEach(ws => ws.send("HOT_RELOAD_NOW")); | |
}); | |
app.set('port', process.env.PORT || 3000); | |
app.listen(app.get('port'), () => { | |
console.log('Started Express server *:' + app.get('port')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment