35 lines
823 B
TypeScript
35 lines
823 B
TypeScript
import { Readable } from "node:stream";
|
|
|
|
export type StreamResolvable = Buffer | Readable | ReadableStream<Uint8Array>;
|
|
|
|
export function intoReadable(input: StreamResolvable): Readable {
|
|
if (Buffer.isBuffer(input)) {
|
|
return Readable.from(input);
|
|
}
|
|
|
|
if (input instanceof Readable) {
|
|
return input;
|
|
}
|
|
|
|
if ("getReader" in input && typeof input.getReader === "function") {
|
|
const reader = input.getReader();
|
|
|
|
return new Readable({
|
|
async read() {
|
|
try {
|
|
const { done, value } = await reader.read();
|
|
if (done) {
|
|
this.push(null);
|
|
} else {
|
|
if (value) this.push(Buffer.from(value));
|
|
}
|
|
} catch (err) {
|
|
this.destroy(err as Error);
|
|
}
|
|
},
|
|
});
|
|
}
|
|
|
|
throw new TypeError("Unsupported stream type");
|
|
}
|