Skip to content

Instantly share code, notes, and snippets.

@mattmorgis
Last active May 8, 2019 15:05
Show Gist options
  • Save mattmorgis/d3f44cd76dddbb20320ad8765f475251 to your computer and use it in GitHub Desktop.
Save mattmorgis/d3f44cd76dddbb20320ad8765f475251 to your computer and use it in GitHub Desktop.
Request Stream as Promise
const request = require("request");
function requestPromiseStream(uri, requestOptions) {
return new Promise(function(resolve, reject) {
var req = request(uri, requestOptions);
req.on("error", reject);
req.on("response", function(res) {
// pause the stream so that it isn't flowing during the async promise hop
res.pause();
if (res.statusCode !== 200) {
if (typeof res.body === "undefined") {
req.on("complete", function(res) {
return reject(
new rpErrors.StatusCodeError(res.statusCode, res.body)
);
});
req.readResponseBody(res);
return;
}
return reject(new rpErrors.StatusCodeError(res.statusCode, res.body));
}
resolve(res);
});
});
}
const main = async () => {
const stream = await requestPromiseStream("https://google.com");
for await (const chunk of stream) {
console.log(chunk);
}
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment