Last active
June 5, 2021 14:45
-
-
Save chrisdlangton/57e9e8e09566324d182a065458d17737 to your computer and use it in GitHub Desktop.
Node.js 14 download to file via proxy
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
require('dotenv').config() | |
const { URL } = require('url'); | |
const http = require('http') | |
const https = require('https') | |
const yaml = require('js-yaml') | |
const fs = require('fs') | |
const config = yaml.load(fs.readFileSync(process.env.CONFIG_FILE, 'utf8')) | |
const download_to_file = (url, dest_path, callback) => { | |
const file = fs.createWriteStream(dest_path) | |
let options = {} | |
options.minVersion = "TLSv1.2" | |
options.maxVersion = "TLSv1.3" | |
options.host = (new URL(url)).hostname | |
options.path = (new URL(url)).pathname | |
const handler = res => { | |
res.pipe(file) | |
file.on('finish', () => file.close(callback)) | |
} | |
const err_handler = err => { | |
console.warn(err) | |
} | |
if ('proxy' in config.app) { | |
options.host = config.app.proxy.host | |
options.port = config.app.proxy.port | |
options.path = url | |
options.headers = { | |
Host: new URL(url).hostname, | |
// 'Proxy-Authorization': 'Basic ' + new Buffer(`${username}:${password}`).toString('base64') | |
} | |
http.get(options, handler).on('error', err_handler).end() | |
} else if (url.startsWith('https')) { | |
https.get(options, handler).on('error', err_handler).end() | |
} else if (url.startsWith('http')) { | |
http.get(options, handler).on('error', err_handler).end() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
.env
exampleThe
package.json
exampleThe
config.yaml
example