1

I want to do something like:

//client -> notifies server that client is connected.

//server -> begins fetching information from DB (series of both async and synchronous requests).

//as sets of data become available on server -> server pushes updates to client via res.render()

Basically I have a menu item on the client, and I want to update that menu as the data that the server fetches gets ready. is there any way to do this? I notice I can't do

res.render('something');
// again
res.render('somethingElse');

Because once render is called, then the response is sent, and render cannot be called again

"Error: Can't set headers after they are sent."

Any suggestions?

1
  • would pushing data from the server to the client be an alternative to your polling solution? Commented Aug 25, 2013 at 23:49

2 Answers 2

3

You might benefit from using WebSockets:

http://en.wikipedia.org/wiki/WebSocket

This post has a little bit of info:

Which websocket library to use with Node.js?

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

Comments

2

HTTP works via request/response. Typically once the response is sent, the connection is terminated.

To stream data from the server to client, you can use websockets. There is a very popular node.js module called socket.io, which simplifies using websockets.

Using socket.io, the client code would look like this:

var socket = io.connect('http://yourserver.com');
socket.on('data', function (data) {
    updateMenu(data);
});

And the server code:

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
    socket.emit('data', data);
    getMoreDataFromDb(function(data){
        socket.emit('data', data);
    });
    // etc..
});

Alternatively, if you want a simpler solution, you can just make multiple small ajax requests to the server, until you get all your data:

(function getData(dataId){ 

    $.ajax({
        url:"yourserver.com/getdata",
        data: dataId || {},
        success:function(data){
            updateMenu(data);
            if(data) getData({ lastDataReceived: data.lastId }); // server is still returning data, request more
        }
    });

})();

Comments

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.