7

I want to reload page when my html files are changed (while development) because of HMR bug in html-webpack-plugin and webpack-dev-middleware (webpack-hot-middleware) interop.

Here are two repositories where I got this problem, there are issues in both.


How can I reload page using this tools?

  • Node.js
  • Express
  • webpack-dev-middleware
zerdox
  • 830
  • 8
  • 22

1 Answers1

11

There are a few ways to refresh a client's browser from the server.

Server-Sent Events:

One simple method that works across browsers and servers uses server-sent events. The minimal process is:

  1. client sends a subscription request to server with EventSource():
var evtSource = new EventSource("<server_URL>/subscribe");
  1. client sets up a listener for incoming messages:
evtSource.onmessage = function () { myPageRefresh() };

On the server side, set up a handler for GET /subscribe requests and keep track of the subscribed client:

const express = require('express');
const app = express();

var client = null;

app.get('/subscribe', (req, res) => {
  // send headers to keep connection alive
  const headers = {
    'Content-Type': 'text/event-stream',
    'Connection': 'keep-alive',
    'Cache-Control': 'no-cache'
  };
  res.writeHead(200, headers);

  // send client a simple response
  res.write('you are subscribed');

  // store `res` of client to let us send events at will
  client = res;

  // listen for client 'close' requests
  req.on('close', () => { client = null; }
});

// send refresh event (must start with 'data: ')
function sendRefresh() {
  client.write('data: refresh');
}

Now the server can send a refresh event at any time by simply calling sendRefresh().

lite-server:

If you are running the server locally on your development computer, refreshing the browser is trivially easy. lite-server is a module that will refresh the browser whenever it detects a change to source files. It's very handy.

terrymorse
  • 6,771
  • 1
  • 21
  • 27
  • 1
    I will try this today. Thank you very much, I guess this what I need. And yes, I need for my local server, for development. – zerdox Feb 08 '20 at 04:49
  • Did this method work for you? If it did, can you accept my answer? – terrymorse Feb 14 '20 at 16:05
  • Sorry.. I forgot. Ready. Thank you very much – zerdox Feb 18 '20 at 16:28
  • 2
    Just make sure you use double `\n` at the end of each message, as it requires a blank line to detect that the message has been fully sent : `res.write('you are subscribed\n\n');` & `res.write('data: refresh\n\n');` https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#sending_events_from_the_server – Typhon Jun 22 '21 at 17:51