Skip to content

Instantly share code, notes, and snippets.

@sp90
Created November 21, 2024 19:28
Show Gist options
  • Save sp90/1bce3bc929c2fc48c57a20a1bb42f7a8 to your computer and use it in GitHub Desktop.
Save sp90/1bce3bc929c2fc48c57a20a1bb42f7a8 to your computer and use it in GitHub Desktop.
Minimalistic livereload
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (_) => {
window.location.reload();
};
// Docs:
//
// Start server:
// node server.mjs --watch="./src/**/*.{js,css}"
//
// Add client script:
// <script src="http://localhost:8080/client.js"></script>
const WebSocket = require('ws');
const fs = require('fs');
const http = require('http');
const watchGlob = process.argv[2] || './**/*.css';
console.log(`Watching for changes in: ${watchGlob}`);
const wss = new WebSocket.Server({ noServer: true });
const server = http.createServer((req, res) => {
if (req.url === '/client.js') {
res.writeHead(200, { 'Content-Type': 'text/javascript' });
const clientJsContent = fs.readFileSync('./client.js');
res.end(clientJsContent);
} else {
res.writeHead(404);
res.end();
}
});
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, socket => {
wss.emit('connection', socket, request);
});
});
wss.on('connection', function connection(ws)  
{
console.log('Client connected');
const watcher = fs.watch(watchGlob, { recursive: true }, (eventType, filename) => {
if (filename) {
ws.send(JSON.stringify({ event: eventType, filename }));
}
});
ws.on('close', () => {
watcher.close();
console.log('Client disconnected and watcher closed.');
});
ws.send('Welcome to the file watcher!');
});
process.on('SIGINT', () => {
console.log('Closing server and watchers...');
wss.clients.forEach(client => {
client.close();
});
server.close(() => {
console.log('Server closed.');
process.exit();
});
});
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment