Doapper
Doapper

Reputation: 109

Refresh Node.js page

Is there any way to refresh a Node.js page after a socket.io event ?

var messageDynamic = "Initial status";

app.get("/", function(request, response) {
    response.setHeader('Content-Type', 'text/plain');
    response.end('The status is : ' + messageDynamic);
});

io.on('connection', function(socket) {

    socket.on('UPDATE', function(message) {
        messageDynamic = message;

        // here I want to refresh the Node.js page (in order to update the message)

    });

Would it be possible that once 'messageDynamic' is updated, the node.js page is updated to ?

Any help would be appreciated

Upvotes: 1

Views: 2011

Answers (1)

Dennis Shtatnov
Dennis Shtatnov

Reputation: 1363

As you have it the plain text page you get when you go to / in your browser requests the server once and then will no longer listen to any events from the server. In order to dynamically update it you will need to send back a full html page with socket.io client code to listen to it:

On the server you would do:

   socket.on('UPDATE', function(message) {
        messageDynamic = message;

        // Send event to every socket.io client
        io.emit('message', message);
    });

On the client you would have a corresponding

var socket = io();
socket.on('message', function(message){
    // Do stuff to the page
})

See http://socket.io/get-started/chat/ for a more complete example of what you are trying to do.

Upvotes: 1

Related Questions