0

I am using the setInterval() function to update a few variables(prices from various API's) every 'x' seconds in NodeJS

I want to display these variables in HTML and have them update real time every 'x' seconds.

How do I go about this using Socket.io or without using it

Satonamo
  • 291
  • 1
  • 8
  • 17
  • You can go with sockets or without. A question on which is better would definitely be closed as it violates SO principles. – Wiktor Zychla Jan 12 '17 at 20:18

2 Answers2

1

If you don't want to use socket.io, you can use AJAX calls but I think it's the more painful way...

If you use socket.io, there are great examples on their GitHub : Chat example.

In your NodeJS :

var io = require('socket.io')(8080); // The port should be different of your HTTP server.

io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
    console.log('new connection');

    var incremental = 0;
    setInterval(function () {
        console.log('emit new value', incremental);

        socket.emit('update-value', incremental); // Emit on the opened socket.
        incremental++;
    }, 1000);

});

This code should be start in your application.

And in your view :

<html>
<body>
    <pre id="incremental"></pre>

    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
        var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.

        socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
            console.log('received new value', value);

            $('#incremental').html(value);
        });
    </script>
</body>
</html>

My code isn't complete but shows the essential to know.

Paul Rey
  • 1,270
  • 1
  • 15
  • 26
  • Thanks. Do you mean to say that the express app should listen at a different port and the socket.io port should be different? – Satonamo Jan 16 '17 at 13:14
  • Yes, it's a mandatory. You can't listen on the same port with two services. You can check [this post](https://stackoverflow.com/questions/1694144/can-two-applications-listen-to-the-same-port) if you want more details :) – Paul Rey Jan 16 '17 at 16:49
0

Try Templating and template engines. Template engine are stuff that enable you to pass variables to Templates. These engines render the template file, with data you provide in form of HTML page.

I will suggest you to try 'ejs', as it very closely signify HTML files. ejs template are simply HTML syntax with placefolder for you to pass Data.

But that will require you to refresh the page continously after regular time. So you can try 'AJAX' which let you refresh part of page, simultaneously sends and receives data from server

chirag jain
  • 419
  • 4
  • 12