Skip to content

Instantly share code, notes, and snippets.

@krnlde
Last active February 22, 2023 03:42
Show Gist options
  • Save krnlde/797e5e0a6f12cc9bd563123756fc101f to your computer and use it in GitHub Desktop.
Save krnlde/797e5e0a6f12cc9bd563123756fc101f to your computer and use it in GitHub Desktop.
util.promisify.custom and http.get example
const http = require('http');
const {promisify} = require('util');
http.get[promisify.custom] = function getAsync(options) {
return new Promise((resolve, reject) => {
http.get(options, (response) => {
response.end = new Promise((resolve) => response.on('end', resolve));
resolve(response);
}).on('error', reject);
});
};
const get = promisify(http.get);
(async () => {
try {
const response = await get('http://krnl.de/');
let body = '';
response.on('data', (chunk) => body += chunk);
await response.end;
console.log(body);
} catch(e) {
// statements
console.log(e);
}
})();
@ashen114
Copy link

Nice snippet! One suggestion.

From:

response.on('data', (chunk) => body += chunk);
await response.end;

To:

for await (const chunk of response) {
  body += chunk
}

awesome!!! (╹ڡ╹ )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment