Skip to content

Instantly share code, notes, and snippets.

@Frenchcooc
Created May 21, 2018 08:44
Show Gist options
  • Save Frenchcooc/ed634242d74db1aa6148024f2b606c13 to your computer and use it in GitHub Desktop.
Save Frenchcooc/ed634242d74db1aa6148024f2b606c13 to your computer and use it in GitHub Desktop.
Make native http/https requests for node js
/*
* 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