kocgo / Browser-Live-Reload

Browser Live Reload with SocketIO and Express

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

NPM Packages

npm install --save socket.io socket.io-client

Server Setup

Requirements

// Express
const express = require("express");
const app = express();
const port = 3000;
// SocketIO and FileSystem
const socket_port = 8080;
const io = require('socket.io').listen(socket_port);
const fs = require('fs');

Static files for front-end

app.use('/node_modules/socket.io-client/dist/',  express.static(__dirname + '/node_modules/socket.io-client/dist'));

Filesysem module watches the current directory recursively and if there is any change callback is being executed

fs.watch(__dirname, { recursive:true }, function () {
  setTimeout(() => io.emit('file-change-event'), 1000);
});

Client (Front-end) Setup

<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>

<script>
    const socket = io.connect('http://localhost:8080');
    socket.on("file-change-event", function () {
        window.location.reload();
    });
</script>

About

Browser Live Reload with SocketIO and Express