Search code examples
node.jssocketssocket.ioreal-time

how to display a realtime variable in nodejs in HTML


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


Solution

  • 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.