Skip to content

doc(http): res.write(data) followed by res.end() is not actually equivalent to res.end(data) #26005

Closed
@peat-psuwit

Description

@peat-psuwit
  • Version: v11.9.0
  • Platform: Linux (My hostname) 4.15.0-45-generic #48-Ubuntu SMP Tue Jan 29 16:28:13 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux (Xubuntu 18.04)
  • Subsystem: Documentation of HTTP module

In the document for method end([data][, encoding][, callback]) of class http.ServerResponse, there's a following text:

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end(callback).

However, this is not actually true when there's only single response.write(data), demonstrable with the following code:

const http = require('http');

const HELLO = 'Hello!\n';

const server1 = http.createServer(function (req, res) {
  res.write(HELLO);
  res.end();
});

const server2 = http.createServer(function (req, res) {
  res.end(HELLO);
});

server1.listen(9001);
server2.listen(9002);

By using curl -v, this happens:

$ curl -v http://localhost:9001/ # response.write(data) follow by response.end()
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9001 (#0)
> GET / HTTP/1.1
> Host: localhost:9001
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Fri, 08 Feb 2019 10:26:25 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
< 
Hello!
* Connection #0 to host localhost left intact

$ curl -v http://localhost:9002/ # response.end(data)
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9002 (#0)
> GET / HTTP/1.1
> Host: localhost:9002
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Fri, 08 Feb 2019 10:26:31 GMT
< Connection: keep-alive
< Content-Length: 7
< 
Hello!
* Connection #0 to host localhost left intact
$ 

So, it appears that response.write(data) follow by response.end() cause Node.js to use chunked encoding, while response.end(data) cause Node.js to not using chunked encoding and include Content-Length header. This small distinction is important with some client. For example, Windows 10's MDM enrollment system will not accept chunked response.

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to the documentations.good first issueIssues that are suitable for first-time contributors.httpIssues or PRs related to the http subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions