Created
May 21, 2024 17:32
-
-
Save jack3898/49ff1f41e881f22eadcd361415edc4c2 to your computer and use it in GitHub Desktop.
Node to/from web readable conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { type Readable } from "node:stream"; | |
export function nodeReadableToWebReadable(nodeReadable: Readable): ReadableStream { | |
return new ReadableStream({ | |
start(controller): void { | |
nodeReadable.on("data", (chunk) => { | |
controller.enqueue(chunk); | |
}); | |
nodeReadable.on("end", () => { | |
controller.close(); | |
}); | |
nodeReadable.on("error", (err) => { | |
controller.error(err); | |
}); | |
}, | |
cancel(): void { | |
nodeReadable.destroy(); | |
} | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Readable } from "stream"; | |
export function webReadableToNodeReadable(readableStream: ReadableStream): Readable { | |
const reader = readableStream.getReader(); | |
return new Readable({ | |
async read(): Promise<void> { | |
const { done, value } = await reader.read(); | |
if (done) { | |
this.push(null); | |
} else { | |
this.push(value); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment