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?

2 Answers2

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?

Community
  • 1
  • 1
Jesus Ruiz
  • 1,377
  • 11
  • 5
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
        }
    });

})();
levi
  • 23,693
  • 18
  • 59
  • 73