Node.js send variable to client

I have a small Node.js HTTP server that does requests to a mongo database (with the mongoose module).

What I want to do is query the database, store it in a variable (array) and send it to the client.

Because ideally, when the user clicks on one of the buttons on the html page, the JavaScript will pick-up the event and change the appearance of the website by showing calculations based on data that is stored in the database.

The only way I could come with was just "transferring" the database content to the client browser but if anyone can come with another solution that would be fine too !

So basically my question is :

  • How can I pass a variable from the Node.js server to the client browser when serving a page ?

Thank you in advance !

If you will be doing more than a couple of these types of transfers, I recommend looking into Socket.IO.

It's a layer that provides quick and easy communication between Node.js servers and web front-ends, by abstracting web sockets when available, and falling back to other transports (such as JSON-P or Flash) when it's not available. Basically, you would call io.emit('something', {yourdata: here}), and it is easily received on the other end. All of the serialization is done for you.

http://socket.io/

Give their demo a shot to see how it works.