Skip to content

Commit

Permalink
http: makes response.writeHead return the response
Browse files Browse the repository at this point in the history
Fixes: #25935

PR-URL: #25974
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
qubyte authored and targos committed Feb 10, 2019
1 parent 9420a73 commit a5247cc
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
16 changes: 13 additions & 3 deletions doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1444,6 +1444,10 @@ the request body should be sent. See the [`'checkContinue'`][] event on
<!-- YAML
added: v0.1.30
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/25974
description: Return `this` from `writeHead()` to allow chaining with
`end()`.
- version: v5.11.0, v4.4.5
pr-url: https://github.com/nodejs/node/pull/6291
description: A `RangeError` is thrown if `statusCode` is not a number in
Expand All @@ -1453,17 +1457,23 @@ changes:
* `statusCode` {number}
* `statusMessage` {string}
* `headers` {Object}
* Returns: {http.ServerResponse}

Sends a response header to the request. The status code is a 3-digit HTTP
status code, like `404`. The last argument, `headers`, are the response headers.
Optionally one can give a human-readable `statusMessage` as the second
argument.

Returns a reference to the `ServerResponse`, so that calls can be chained.

```js
const body = 'hello world';
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain' });
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
})
.end(body);
```

This method must only be called once on a message and it must
Expand Down
2 changes: 2 additions & 0 deletions lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,8 @@ function writeHead(statusCode, reason, obj) {
}

this._storeHeader(statusLine, headers);

return this;
}

// Docs-only deprecated: DEP0063
Expand Down
22 changes: 22 additions & 0 deletions test/parallel/test-http-response-writehead-returns-this.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';
require('../common');
const http = require('http');
const assert = require('assert');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'a-header': 'a-header-value' }).end('abc');
});

server.listen(0, () => {
http.get({ port: server.address().port }, (res) => {
assert.strictEqual(res.headers['a-header'], 'a-header-value');

const chunks = [];

res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
assert.strictEqual(Buffer.concat(chunks).toString(), 'abc');
server.close();
});
});
});

0 comments on commit a5247cc

Please sign in to comment.