Skip to content

Instantly share code, notes, and snippets.

@d0ruk
Created July 20, 2022 18:27
Show Gist options
  • Save d0ruk/fe26458a95d204e8831f448c4b799feb to your computer and use it in GitHub Desktop.
Save d0ruk/fe26458a95d204e8831f448c4b799feb to your computer and use it in GitHub Desktop.
HTTP requests pipeline
import { promisify } from "node:util";
import { pipeline as _p, Transform } from "node:stream";
import request from "got";
import { log, sleep } from "./util.mjs";
const pipeline = promisify(_p);
const transform = new Transform({
transform: function (chunk, enc, cb) {
// console.log({ chunk: chunk.toString(), enc });
this.push(chunk.toString().toUpperCase());
cb();
},
// encoding: "",
objectMode: true,
});
pipeline(run() /*, transform*/, process.stdout).catch(log.error);
setTimeout(() => {
finished = true;
}, 7000);
let finished = false;
async function* run(generator = fetchAPI()) {
do {
const { value, done } = await generator.next();
// finished = done;
yield "> " + value.value + "\n";
await sleep(2000);
} while (!finished);
}
async function* fetchAPI() {
while (true) {
try {
yield await request("https://api.chucknorris.io/jokes/random").json();
} catch (err) {
throw err;
}
}
}
async function* generator2() {
const NOW = Date.now();
log.info(`Start`);
yield "a\n";
await sleep(1000);
log.info(`${Date.now() - NOW} later`);
yield "b\n";
await sleep(2000);
log.info(`${Date.now() - NOW} later`);
yield "c\n";
await sleep(3000);
log.info(`${Date.now() - NOW} later`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment