Skip to content

Instantly share code, notes, and snippets.

@Phoenix35
Last active December 23, 2018 15:42
Show Gist options
  • Save Phoenix35/554bb3090bb982fd538b74390e936433 to your computer and use it in GitHub Desktop.
Save Phoenix35/554bb3090bb982fd538b74390e936433 to your computer and use it in GitHub Desktop.
"use strict";
/*
User-defined settings
*/
const protocol = "https"; // Change to http for old-school
/*
Begin!
*/
const agentGet = require(protocol).get;
/**
*
* @param {URL|string|Object} url .
* @param {?string} encoding Set it explicitly to `null` to keep a buffer
* @return {Promise<string | Buffer>}
*/
function getFullBody (url, encoding = "utf8") {
return new Promise((resolve, reject) => {
agentGet(url, async (res) => {
const data = [];
if (encoding)
res.setEncoding(encoding);
res.on("error", reject);
for await (const chunk of res)
data.push(chunk);
if (encoding)
resolve(data.join(""));
else
resolve(Buffer.concat(data));
}).on("error", reject);
});
}
/*
Example
*/
(async function main () {
const res = await getFullBody("https://jsonplaceholder.typicode.com/posts/1");
console.log(res);
})().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment