Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 707
copyflake Avatar asked Apr 07 '13 10:04

copyflake


People also ask

Is nodeJS good for real-time?

Read – Benefits of nodeJSNode JS is an excellent choice for developers in real-time applications and has proven to be successful in similar use-cases across the industry.

Does node update automatically?

Note: By default, subsequent node pools do not have auto-upgrades enabled.


2 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)
});
like image 54
Iftah Avatar answered Oct 19 '22 23:10

Iftah


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.
like image 6
Alexander Mills Avatar answered Oct 19 '22 23:10

Alexander Mills