Skip to content

Instantly share code, notes, and snippets.

@fronterior
Created March 2, 2022 22:08
Show Gist options
  • Save fronterior/cf5612db231d4dea681e6b5877dcb47a to your computer and use it in GitHub Desktop.
Save fronterior/cf5612db231d4dea681e6b5877dcb47a to your computer and use it in GitHub Desktop.
const fs = require("fs");
const stream = fs.createWriteStream("./fake-read-stream");
const fakeReadableStream = new (class {
readable = true;
constructor() {
this.data =
"abc ewij fj wiefj ewi tj94htr834h u4 hru4 u9jr92i3 i09rj 239ij erw9i fgj3u94it 34i9 tj";
this.cursor = 0;
this.mode = "pull";
this.listeners = [];
this.ended = false;
}
on(type, f) {
if (type === "data") {
this.listeners.push({ type: "data", handler: f });
setTimeout(async () => {
this.mode = "push";
let r;
while (((r = this.read()), this.mode === "push")) {
const r = this.read();
this.listeners
.filter(({ type }) => type === "data")
.forEach(({ handler }) => f("data", r));
await new Promise((res) => setTimeout(res));
}
});
} else if (type === "end") {
this.listeners.push({ type: "end", handler: f });
}
}
read() {
if (this.cursor === this.data.length) {
this.mode = "pull";
if (!this.ended) {
this.ended = true;
this.listeners
.filter(({ type }) => type === "end")
.forEach((f) => f("end", null));
}
return null;
}
this.mode = "push";
return this.data[this.cursor++];
}
pipe(writableStream) {
(async () => {
let r;
while (((r = this.read()), this.mode === "push")) {
writableStream.write(Buffer.from(r));
await new Promise((res) => setTimeout(res));
}
writableStream.end();
})();
}
})();
// ???
fakeReadableStream.pipe(stream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment