Files
xen-orchestra/@xen-orchestra/backups/_forkStreamUnpipe.js
Julien Fontanet a958fe86d7 feat(proxy): version 1 (#4495)
Co-authored-by: badrAZ <azizbibadr@gmail.com>
Co-authored-by: Mathieu <70369997+MathieuRA@users.noreply.github.com>
2021-02-23 08:58:10 +01:00

29 lines
723 B
JavaScript

const eos = require('end-of-stream')
const { PassThrough } = require('stream')
// create a new readable stream from an existing one which may be piped later
//
// in case of error in the new readable stream, it will simply be unpiped
// from the original one
exports.forkStreamUnpipe = function forkStreamUnpipe(stream) {
const { forks = 0 } = stream
stream.forks = forks + 1
const proxy = new PassThrough()
stream.pipe(proxy)
eos(stream, error => {
if (error !== undefined) {
proxy.destroy(error)
}
})
eos(proxy, _ => {
stream.forks--
stream.unpipe(proxy)
if (stream.forks === 0) {
stream.destroy(new Error('no more consumers for this stream'))
}
})
return proxy
}