From 9c9d2b88e1b271d346bcd891e2c7a907436094aa Mon Sep 17 00:00:00 2001 From: Randall Schmidt Date: Thu, 10 Jun 2021 11:28:05 -0400 Subject: [PATCH] support streaming response --- classes/response.js | 11 ++++++++--- test/tests.js | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/classes/response.js b/classes/response.js index f754c8a..b22443f 100644 --- a/classes/response.js +++ b/classes/response.js @@ -1,4 +1,5 @@ const fs = require('fs'); +const stream = require('stream'); const Headers = require('./headers.js'); class Response { @@ -7,19 +8,23 @@ class Response { this.cacheFilePath = cacheFilePath; this.headers = new Headers(raw.headers); this.fromCache = fromCache; - this.consumed = false; + this.bodyUsed = false; if (this.bodyBuffer.type === 'Buffer') { this.bodyBuffer = Buffer.from(this.bodyBuffer); } } + get body() { + return stream.Readable.from(this.bodyBuffer); + } + consumeBody() { - if (this.consumed) { + if (this.bodyUsed) { throw new Error('Error: body used already'); } - this.consumed = true; + this.bodyUsed = true; return this.bodyBuffer; } diff --git a/test/tests.js b/test/tests.js index 8605e9b..b1df47a 100644 --- a/test/tests.js +++ b/test/tests.js @@ -246,4 +246,26 @@ describe('Data tests', function() { assert.strictEqual(expectedPngBuffer.equals(body), true); assert.strictEqual(res.fromCache, true); }); + + it('Can stream a body', async function() { + res = await fetch(TEXT_BODY_URL); + body = ''; + + for await (const chunk of res.body) { + body += chunk.toString(); + } + + assert.strictEqual(TEXT_BODY_EXPECTED, body); + assert.strictEqual(res.fromCache, false); + + res = await fetch(TEXT_BODY_URL); + body = ''; + + for await (const chunk of res.body) { + body += chunk.toString(); + } + + assert.strictEqual(TEXT_BODY_EXPECTED, body); + assert.strictEqual(res.fromCache, true); + }); }).timeout(10000);