Skip to content

Commit ccf2823

Browse files
qubyteBethGriggs
authored andcommitted
http: makes response.writeHead return the response
Fixes: #25935 PR-URL: #25974 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent fe58bca commit ccf2823

File tree

3 files changed

+37
-3
lines changed

3 files changed

+37
-3
lines changed

doc/api/http.md

+13-3
Original file line numberDiff line numberDiff line change
@@ -1434,6 +1434,10 @@ the request body should be sent. See the [`'checkContinue'`][] event on
14341434
<!-- YAML
14351435
added: v0.1.30
14361436
changes:
1437+
- version: REPLACEME
1438+
pr-url: https://github.com/nodejs/node/pull/25974
1439+
description: Return `this` from `writeHead()` to allow chaining with
1440+
`end()`.
14371441
- version: v5.11.0, v4.4.5
14381442
pr-url: https://github.com/nodejs/node/pull/6291
14391443
description: A `RangeError` is thrown if `statusCode` is not a number in
@@ -1443,17 +1447,23 @@ changes:
14431447
* `statusCode` {number}
14441448
* `statusMessage` {string}
14451449
* `headers` {Object}
1450+
* Returns: {http.ServerResponse}
14461451

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

1457+
Returns a reference to the `ServerResponse`, so that calls can be chained.
1458+
14521459
```js
14531460
const body = 'hello world';
1454-
response.writeHead(200, {
1455-
'Content-Length': Buffer.byteLength(body),
1456-
'Content-Type': 'text/plain' });
1461+
response
1462+
.writeHead(200, {
1463+
'Content-Length': Buffer.byteLength(body),
1464+
'Content-Type': 'text/plain'
1465+
})
1466+
.end(body);
14571467
```
14581468

14591469
This method must only be called once on a message and it must

lib/_http_server.js

+2
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,8 @@ function writeHead(statusCode, reason, obj) {
269269
}
270270

271271
this._storeHeader(statusLine, headers);
272+
273+
return this;
272274
}
273275

274276
// Docs-only deprecated: DEP0063
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'use strict';
2+
require('../common');
3+
const http = require('http');
4+
const assert = require('assert');
5+
6+
const server = http.createServer((req, res) => {
7+
res.writeHead(200, { 'a-header': 'a-header-value' }).end('abc');
8+
});
9+
10+
server.listen(0, () => {
11+
http.get({ port: server.address().port }, (res) => {
12+
assert.strictEqual(res.headers['a-header'], 'a-header-value');
13+
14+
const chunks = [];
15+
16+
res.on('data', (chunk) => chunks.push(chunk));
17+
res.on('end', () => {
18+
assert.strictEqual(Buffer.concat(chunks).toString(), 'abc');
19+
server.close();
20+
});
21+
});
22+
});

0 commit comments

Comments
 (0)