initial commit
This commit is contained in:
34
src/util/stream.ts
Normal file
34
src/util/stream.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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");
|
||||
}
|
||||
Reference in New Issue
Block a user