1

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

3
  • Force refreshing webpage on the client-side with use of JS. Commented Jul 3, 2016 at 12:36
  • You don't need to refresh the page for updates if you emit an event with the necesary data to change the DOM. Commented Jul 3, 2016 at 12:47
  • Thank you for your help but could you elaborate more please? Commented Jul 3, 2016 at 21:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but at the "// Do stuff to the page" position, it's on the client side, how could I do modify the server main page ?
If you need to change messageDynamic on the server, then doing socket.emit("UPDATE", "new message") on a client would change it. But, client's won't refresh unless they are also listening for an event.
Sorry I was not very clear, I want that once messageDynamic is updated on the server side (which is the case with my initial code), the " response.end('The status is : ' + messageDynamic)" is updated or executed again.
The response.end(...) line will only be run when a user explicitly goes to that url or refreshes. You can not force it to refresh from the server without adding code to the page you send to the browser that waits for a message before refreshing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.