koajs / koa

Expressive middleware for node.js using ES2017 async functions
https://koajs.com
MIT License
35.07k stars 3.22k forks source link

Add custom stream support #1825

Open KristapsR opened 1 month ago

KristapsR commented 1 month ago

Description

There are situations when we need to send response stream that is not an instance of node Readable stream and current way of checking for stream value instanceof Stream fails. e.g. when using alternative module like readable-stream or some other cases

My usecase

import archiver from 'archiver'

const archive = archiver('zip')
const stream = ...
archive.append(stream, { name: 'archive.zip'})

res.body = archive

Solution

Tested also with this code

const archiver = require('archiver')
const Stream = require('stream')
const CustomStream = require('./test-helpers/stream.js')
const isReadableStream = require('./lib/is-readable-stream.js')

const stream = new Stream()
const archive = archiver('zip')
const customstream = new CustomStream.Readable()

console.log(stream instanceof Stream) // true
console.log(customstream instanceof Stream) // false
console.log(archive instanceof Stream) // false

console.log(isReadableStream(stream)) // true
console.log(isReadableStream(customstream)) // true
console.log(isReadableStream(archive)) // true