Skip to content

Instantly share code, notes, and snippets.

@monjer
Created July 6, 2022 03:29
Show Gist options
  • Save monjer/228280da232e8f1e630101b2ec4f47fd to your computer and use it in GitHub Desktop.
Save monjer/228280da232e8f1e630101b2ec4f47fd to your computer and use it in GitHub Desktop.
import http from 'http';
/**
* @see https://stackoverflow.com/questions/38533580/nodejs-how-to-promisify-http-request-reject-got-called-two-times
*/
export default async (options, postData) => {
return new Promise((resolve, reject) => {
let body = [];
const request = http.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
res.on('data', (chunk) => {
body.push(chunk);
});
res.on('end', function () {
try {
body = JSON.parse(Buffer.concat(body).toString());
} catch (e) {
reject(e);
}
resolve(body);
});
});
request.on('error', function (err) {
reject(err);
});
if(postData){
request.write(postData);
}
request.end();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment