When I try to utilize http stream connection for some reason write does not flush until I call
response.end()
I am taking the code straight from the demo and do not understand what my problem is.
When I curl to the server my headers are correct.
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello');
res.write(':');
setTimeout(function(){
res.end('World\n')},
2000);
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Why is the server not sending the write data?
I seems to be browser specific behavior -- firefox shows the data ("Hello:") immediately while chrome seems to buffer and wait until the response is ended. Note that chrome also shows the data immediately if you write more data at first (e.g. I wrote 1000 "Hello"s).
I think I understand what you mean...
From the node.js docs:
The first time response.write() is called, it will send the buffered header information and the first body to the client. The second time response.write() is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.
http://nodejs.org/docs/v0.4.7/api/all.html#response.write
(Nice port usage BTW :) )
Try to check your code with telnet or nc. curl usually buffers last line
After fixing the missing curly brace, your code is working for me from a browser. Curl from the commandline seems to wait for the full response but wireshark confirms that it does use chunked encoding and the response was split into 2 packages in both cases.
I assume that the curl output is line buffered and waiting for the newline after 'World' before it prints anything. You can confirm this by printing another newline after 'hello:'.
this is due to you missed a enclosing "}" in your code at position after res.end('World\n')
and before the comma.
来源:https://stackoverflow.com/questions/6068820/node-js-problems-with-response-write