Reputation: 4136
I'm new to node.js and have this very simple code. I just want to say a Hi User every second to the users who have connected to the server. Here's the code I have:
var http = require('http');
function newfunc(request, response) {
response.writeHead(200, {
"Content-Type": "text/plain",
"connection" : "keep-alive"
});
setInterval(function() {
response.write('Hi User\n');
response.end('');
}, 1000);
}
http.createServer(newfunc).listen(7070);
I see the Hi User
message only once, and seems as if setInterval
is writing it only once.
What am I doing wrong in this?
Upvotes: 0
Views: 273
Reputation: 27370
EDIT: I stand corrected in the comments... Just remove the response.end()
call and you should see something like what you were expecting.
ORIGINAL RESPONSE: What you are trying to do cannot be done in this fashion... The response to an HTTP request is only ever sent once: when response.end()
is called (the first time). Commenter points out that this is not really correct: what would be correct to say is that no further data can be sent in the response after end()
is called.
If you want to show an HTML page whose contents change every second based on server-side actions, you will need to use something like WebSockets (e.g. the Node-compatible http://socket.io/ library) and some client-side Javascript, which is somewhat more complicated than the code you have above. In general, for non-trivial UI's that do more than just append to the response or do bi-directional communication, this type of approach is preferrable
Upvotes: 1