Created
May 21, 2018 08:44
-
-
Save Frenchcooc/ed634242d74db1aa6148024f2b606c13 to your computer and use it in GitHub Desktop.
Make native http/https requests for node js
This file contains 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
/* | |
* Make native http/https requests | |
* | |
* @usage: NativeRequest([URL|options]) | |
* @demo: NativeRequest('https://example.org') | |
* | |
* @output: <http.ClientRequest> - see https://nodejs.org/api/http.html#http_http_request_options_callback | |
*/ | |
const { URL } = require('url') | |
const http = require('http') | |
const https = require('https') | |
function NativeRequest (options, callback) | |
{ | |
try { | |
const requestURL = new URL((typeof options == 'string') ? options : options.url) | |
options.protocol = requestURL.protocol | |
options.host = requestURL.host | |
options.path = requestURL.path | |
if (requestURL.protocol == 'http:') | |
{ return http.get(options, callback) } | |
else if (requestURL.protocol == 'https:') | |
{ return https.get(options, callback) } | |
else | |
{ throw 'Unsupported protocol: ' + url.protocol } | |
} | |
catch (err) { throw err } | |
} | |
module.exports = NativeRequest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment