how to display a realtime variable in nodejs in HTML

谁说我不能喝 提交于 2019-12-12 03:31:45

问题


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


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/41619628/how-to-display-a-realtime-variable-in-nodejs-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!