Skip to content

Instantly share code, notes, and snippets.

@carpeliam
Last active August 1, 2021 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carpeliam/b9d48085b1556e539303fb48d82a45b6 to your computer and use it in GitHub Desktop.
Save carpeliam/b9d48085b1556e539303fb48d82a45b6 to your computer and use it in GitHub Desktop.
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;
}
}
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