I want to know if it is possible to stream data from the server to the client with Node.js. From what I can understand all over the internet is that this has to be possible, yet I fail to find a correct example or solution.
What I want is a single http post to node.js with AJAX. Than leave the connection open and continuously stream data to the client.
The client will receive this stream and update the page continuously.
Update 1
As an update to this answer: http://stackoverflow.com/questions/2558606/stream-data-with-node-js/2563459#2563459
I tried this already and I tried it again after your anser. I can not get this to work. The response.write is not send before you call close. I have set up an example program that i use to achieve this.
Node.js code:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var currentTime = new Date();
setInterval(function(){
res.write(
currentTime.getHours()
+ ':' +
currentTime.getMinutes()
+ ':' +
currentTime.getSeconds()
);
},1000);
}).listen(8000);
Here the html code:
<html>
<head>
<title>Testnode</title>
</head>
<body>
<!-- This fields needs to be updated -->
Server time: <span id="time"> </span>
<!-- import jQuery from google -->
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<!-- import jQuery -->
<script type="text/javascript">
$(document).ready(function(){
// I call here node.localhost nginx ports this to port 8000
$('#time').load('http://node.localhost');
});
</script>
</body>
</html>
Using this method I don't get anything back until I call close(). is this possible or should I rather go with a long poll approach where I call the load function again as one comes in.
i really rather want to stream this. I hope someone can help.