Last active
August 1, 2021 16:03
-
-
Save carpeliam/b9d48085b1556e539303fb48d82a45b6 to your computer and use it in GitHub Desktop.
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 { Writable } from 'stream'; | |
class InMemoryStream extends Writable { | |
private chunks: Uint8Array[] = []; | |
private contentPromise: Promise<string>; | |
constructor() { | |
super(); | |
this.contentPromise = new Promise((resolve, reject) => { | |
this.once('finish', () => { resolve(Buffer.concat(this.chunks).toString('utf8')); }); | |
this.once('error', err => { reject(err); }); | |
}); | |
} | |
_write(chunk: any, encoding: BufferEncoding, next: Function) { | |
this.chunks.push(Buffer.from(chunk)); | |
next(); | |
} | |
contents() { | |
return this.contentPromise; | |
} | |
} |
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 fetch from 'node-fetch'; | |
async function downloadTo(writeStream: NodeJS.WritableStream) { | |
const response = await fetch('https://gist.githubusercontent.com/carpeliam/b9d48085b1556e539303fb48d82a45b6/raw/2521b5c640060e48a237f0314025dffeac501791/writeToInMemoryStream.ts'); | |
response.body.pipe(writeStream); | |
} | |
const writeStream = new InMemoryStream(); | |
await downloadTo(writeStream); | |
const contents = await writeStream.contents(); | |
console.log(contents); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment