diff --git a/docs/api/Dispatcher.md b/docs/api/Dispatcher.md index 466e6bd2eed..00a02f72ad0 100644 --- a/docs/api/Dispatcher.md +++ b/docs/api/Dispatcher.md @@ -436,6 +436,10 @@ The `RequestOptions.method` property should not be value `'CONNECT'`. - `body` - `bodyUsed` +`body` contains the following additional extentions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + #### Example 1 - Basic GET Request ```js diff --git a/lib/api/readable.js b/lib/api/readable.js index 0580f421e5b..e9db983d502 100644 --- a/lib/api/readable.js +++ b/lib/api/readable.js @@ -144,6 +144,20 @@ module.exports = class BodyReadable extends Readable { } return this[kBody] } + + async dump(opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + try { + for await (const chunk of this) { + limit -= Buffer.byteLength(chunk) + if (limit < 0) { + return + } + } + } catch { + // Do nothing... + } + } } // https://streams.spec.whatwg.org/#readablestream-locked diff --git a/test/client-request.js b/test/client-request.js index ebb105e42f8..1fa7943a759 100644 --- a/test/client-request.js +++ b/test/client-request.js @@ -12,6 +12,36 @@ const { NotSupportedError } = require('../lib/core/errors') const nodeMajor = Number(process.versions.node.split('.')[0]) +test('request dump', (t) => { + t.plan(3) + + const signal = new EE() + const server = createServer((req, res) => { + res.end('hello') + }) + t.teardown(server.close.bind(server)) + + server.listen(0, () => { + const client = new Client(`http://localhost:${server.address().port}`) + t.teardown(client.destroy.bind(client)) + + let dumped = false + client.on('disconnect', () => { + t.equal(dumped, true) + }) + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + t.error(err) + body.dump().then(() => { + dumped = true + t.pass() + }) + }) + }) +}) + test('request abort before headers', (t) => { t.plan(6)