Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

get

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!

like image 860
Chris Nolet Avatar asked Mar 10 '13 01:03

Chris Nolet


People also ask

What is the difference between HTTP and HTTPS in Node js?

js. HTTP: When the data transfer in HTTP protocol it just travels in the clear text format. HTTPS: It simply makes encryption when the request is traveling from the browser to the web server so it is tough to sniff that information.

What is the difference between HTTPS get and HTTPS request?

"https. get" is only for GET requests - which are a special type of HTTP request that should be used only for retrieving data. in "https. request" you can specify any HTTP method you want in the 'method' property - you could use "POST" (creating), PATCH (updating) or also GET.

How is an HTTP GET request made in Node js?

It's called by creating an options object like: const options = { host: 'somesite.com', port: 443, path: '/some/path', method: 'GET', headers: { 'Content-Type': 'application/json' } }; And providing a callback function.

What are the different types of HTTP requests in Node js?

http module The HTTP options specify the headers, destination address, and request method type. Next, we use http. request to send the data to the server and await the response. The response is stored in the req variable, and upon error, it is logged into the console.


2 Answers

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, ...) 
like image 74
Khaja Minhajuddin Avatar answered Sep 29 '22 09:09

Khaja Minhajuddin


There's a bunch of modules you could use instead, like request or needle. They'll figure out which protocol to use, and how to handle redirects (if required) and such.

like image 41
robertklep Avatar answered Sep 29 '22 07:09

robertklep