Node JS: Automatic selection of `http.get` vs `https.get`

Chris Nolet picture Chris Nolet · Mar 10, 2013 · Viewed 16.3k times · Source

I have a Node JS app that needs to download a file, given a URL at run-time.

The URL may be either http:// or https://.

How do I best cater for the different protocols?

At the moment I have:

var http = require('http');
var https = require('https');

var protocol = (parsedUrl.protocol == 'https:' ? https : http);
protocol.get(parsedUrl, function(res) {
  ...
});

... but it feels clunky.

Thanks!

Answer

Khaja Minhajuddin picture Khaja Minhajuddin · Jul 19, 2016

I had a similar need, but didn't need the full blown request or needle libraries, I have the following code (which is slightly different)

var adapterFor = (function() {
  var url = require('url'),
    adapters = {
      'http:': require('http'),
      'https:': require('https'),
    };

  return function(inputUrl) {
    return adapters[url.parse(inputUrl).protocol]
  }
}());
//.. and when I need it
adapterFor(url).get(url, ...)