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!
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.
"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.
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.
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.
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, ...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With