Created
September 19, 2020 12:34
-
-
Save supermarsx/2991a8ffa72b2153eea06c6863b5c7b9 to your computer and use it in GitHub Desktop.
Do a promisified HTTP/HTTPS request
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
// jshint esversion:8 | |
// jshint node:true | |
'use strict'; | |
const https = require('https'); | |
const http = require('http'); | |
/* | |
request | |
Do a HTTP/HTTPS request | |
parameters | |
options (object) - HTTP/HTTPS request options | |
postData (object) - POST data object | |
*/ | |
function request(options, postData) { | |
return new Promise(function(resolve, reject) { | |
var httpx = options.insecure ? http : https; | |
var req = httpx.request(options, function(res) { | |
/* | |
if (res.statusCode < 200 || res.statusCode >= 300) { | |
return reject(new Error('statusCode=' + res.statusCode)); | |
} | |
*/ | |
res.body = ''; | |
res.on('data', function(chunk) { | |
res.body += (chunk); | |
}); | |
res.on('end', function() { | |
resolve(res); | |
}); | |
}); | |
req.on('error', function(err) { | |
reject(err); | |
}); | |
if (postData) { | |
req.write(postData); | |
} | |
req.end(); | |
}); | |
} | |
exports.request = request; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment