Home » Nodejs » node.js – how to make a simple live page update?

node.js – how to make a simple live page update?

Posted by: admin November 29, 2017 Leave a comment

Questions:

I’m very very new to node.js, but there’s actually only one simple thing that I am trying to achieve by learning the language.

I’d like to create a webpage, where by the code in a specific “div” can be hotswapped on the fly to users currently looking at that page. (ie. the div contains some text, but then an image replaces it.)
Ideally, the swap would be executed manually by the the webpage’s admin through the click of a button, or some code fired off on the server or something. Regular viewers to the webpage would not be able to do this – they only see the live changes on the page.

real-life example:

live internet broadcast is off-air, therefore the “div” contains “off-air” text.
live hotswap of code happens when broadcast goes on-air, and the viewers of the webpage now see the html5 broadcast player in the “div” instead.

What’s the simplest way to go about doing this for a node.js newbie?

Many thanks 🙂

Answers:

Take a look at Socket.IO http://socket.io/#how-to-use

when the server decides to broadcast a change use:

io.sockets.emit('update-msg', { data: 'this is the data'});

on the client first connect socket.io and then wait for the “update-msg” event and update your dom:

var socket = io.connect('http://localhost');
socket.on('update-msg', function (msg) {
    console.log(msg);
    $('#mydiv').html(msg.data)
});

Questions:
Answers:

I created a system/methodology to live update (hot reload) front-end code using RequireJS and Node.js. I made sure it worked with both React and Backbone. You can read about it here:

https://medium.com/@the1mills/hot-reloading-with-react-requirejs-7b2aa6cb06e1

the basic steps involved in doing this yourself:

  1. gulp.js watchers listen for filesystem changes
  2. socket.io server in gulpfile sends a message to all browser clients
    with the path of the file that changed
  3. client deletes cache representing that file/module, and re-requires
    it (using AJAX to pull it from the server filesystem)
  4. front-end app is configured / designed to re-evaluate all references
    to the modules that it wishes to hot-reload, in this case, only JS
    views, templates and CSS are available to hot reload – the router,
    controllers, datastores (Backbone Collections and Models) are not
    configured yet. I do suspect all files could be hot reloaded with
    the only exception being data stores.