diff --git a/lib/core/request.js b/lib/core/request.js index 919805d275d..8ab5734037e 100644 --- a/lib/core/request.js +++ b/lib/core/request.js @@ -36,7 +36,7 @@ class Request { if (body == null) { this.body = null - } else if (util.isStream(body)) { + } else if (util.isReadable(body)) { this.body = body } else if (util.isBuffer(body)) { this.body = body.length ? body : null diff --git a/lib/core/util.js b/lib/core/util.js index b2e7fddb2ae..9757bb77247 100644 --- a/lib/core/util.js +++ b/lib/core/util.js @@ -9,8 +9,18 @@ const { InvalidArgumentError } = require('./errors') function nop () {} -function isStream (body) { - return !!(body && typeof body.on === 'function') +function isReadable (obj) { + return !!(obj && typeof obj.pipe === 'function' && + typeof obj.on === 'function') +} + +function isWritable (obj) { + return !!(obj && typeof obj.write === 'function' && + typeof obj.on === 'function') +} + +function isStream (obj) { + return isReadable(obj) || isWritable(obj) } function parseURL (url) { @@ -161,6 +171,7 @@ module.exports = { getServerName, errnoException, isStream, + isReadable, isDestroyed, parseHeaders, parseKeepAliveTimeout, diff --git a/test/stream-compat.js b/test/stream-compat.js index 55dba7f82a4..71d2410ee36 100644 --- a/test/stream-compat.js +++ b/test/stream-compat.js @@ -3,6 +3,7 @@ const { test } = require('tap') const { Client } = require('..') const { createServer } = require('http') +const { Readable } = require('stream') const EE = require('events') test('stream body without destroy', (t) => { @@ -17,7 +18,8 @@ test('stream body without destroy', (t) => { t.teardown(client.destroy.bind(client)) const signal = new EE() - const body = new EE() + const body = new Readable({ read () {} }) + body.destroy = undefined body.on('error', (err) => { t.ok(err) }) diff --git a/test/util.js b/test/util.js new file mode 100644 index 00000000000..aea7c6055d2 --- /dev/null +++ b/test/util.js @@ -0,0 +1,21 @@ +'use strict' + +const t = require('tap') +const { test } = t +const { Stream } = require('stream') +const { EventEmitter } = require('events') + +const util = require('../lib/core/util') + +test('isStream', (t) => { + t.plan(3) + + const stream = new Stream() + t.ok(util.isStream(stream)) + + const buffer = Buffer.alloc(0) + t.notOk(util.isStream(buffer)) + + const ee = new EventEmitter() + t.notOk(util.isStream(ee)) +})