Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Js problems with response.write

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?

like image 453
James Andino Avatar asked May 20 '11 07:05

James Andino


People also ask

What is node write in Node JS?

Node.js response.write () Method. The response.write () ( Added in v0.1.29) method is an inbuilt Application program Interface of the ‘ http ’ module which sends a chunk of the response body that is omitted when the request is a HEAD request.

What is a second time response in Node JS?

The second time response.write () is called, Node.js assumes data will be streamed and sends the new data separately. That is, the response is buffered up to the first chunk of the body.

How do I make a GET request using Node JS?

The simplest way to perform an HTTP request using Node.js is to use the Axios library: However, Axios requires the use of a 3rd party library. A GET request is possible just using the Node.js standard modules, although it's more verbose than the option above:

What happens when response writehead () is not called?

If this method is called and response.writeHead () has not been called, it will switch to implicit header mode and flush the implicit headers. The first time response.write () is called, it will send the buffered header information and the first chunk of the body to the client.


1 Answers

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).

like image 115
Geoff Chappell Avatar answered Oct 02 '22 05:10

Geoff Chappell