Last active
December 23, 2018 15:42
-
-
Save Phoenix35/554bb3090bb982fd538b74390e936433 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "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