Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node: Automatically refresh browser on file change

I want my node app to automatically refresh my browser when a file changes (no external application).

I'd like to avoid using webpack dev server, as it doesn't allow me to use my own koa server, and is just generally a hassle to work with.

How can I automatically refresh my browser on file change?

like image 385
Elegant.Scripting Avatar asked Feb 15 '16 22:02

Elegant.Scripting


2 Answers

Try use watchr:

koa-app.js:

/.../
var watchr = require('watchr');
watchr.watch({
    paths: [__dirname], listeners: {
        change: function() {
            // Emits an event to all connected clients 
            io.sockets.emit('browserReload');
        }
    }
})

client-side.js:

  /.../
  socket.on('browserReload', function () {
     // Reload without using cache
     document.location.reload(true);
  });
like image 192
stdob-- Avatar answered Nov 13 '22 17:11

stdob--


So I figured it out.

It turns out koa-socket's API might work for some people, but it's generally a bunch of unneeded bloat. Also, watching the process is great, but if you already have node scripts doing that, it's redundant, and will break your code.

I ended up attaching socket.io to my Koa server with some pretty simple code:

server.js

var app = require('koa')();
var server = require('http').createServer(app.callback());
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);

This worked great. The next step was to connect to my Koa server on the client. That code was also really simple as well:

client.js

var socket = require("socket.io-client")("http://localhost:3000");

So now socket.io was working on my server, and the client could connect to it. My server, thanks to node packages and scripts (like supervisor/nodemon), was restarted on any file change.

The next step was simple: when a file changes, the server restarts, when the server restarts, emit a socket.io event to all clients that forces a page reload. The code looked like this:

server.js

var serverRestarted = true;

if (serverRestarted === true) {
    io.emit("browserReload");
    serverRestarted = false;
}

client.js

socket.on("browserReload", function() {
    document.location.reload(true);
});

And that was that. Sure, it was a pain working around packages that didn't work as intended or made undocumented changes to API's I was used to working with... so I didn't use them.

And I've ended up with something that works great during development.

like image 28
Elegant.Scripting Avatar answered Nov 13 '22 17:11

Elegant.Scripting