Created
August 8, 2022 23:40
-
-
Save fabriciobastian/927d5b6a30c5271cdc5127fc4080a21d to your computer and use it in GitHub Desktop.
Download a file from a provided url
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
const http = require('http'); | |
const https = require('https'); | |
const fs = require('fs'); | |
const chalk = require('chalk'); | |
const yargs = require('yargs'); | |
const { hideBin } = require('yargs/helpers'); | |
const downloadFailed = errorMsg => { | |
fs.unlinkSync(tempFile); | |
console.error(chalk.red(`\u2717 Download failed: ${errorMsg}`)); | |
process.exit(1); | |
}; | |
const downloadSucceeded = fileName => { | |
console.log(chalk.green(`\u2713 File downloaded successfully to ${fileName}`)); | |
}; | |
const args = yargs(hideBin(process.argv)) | |
.option('url', { | |
alias: 'u', | |
type: 'string', | |
demandOption: true, | |
description: 'URL of the file to download' | |
}) | |
.option('output', { | |
alias: 'o', | |
type: 'string', | |
demandOption: true, | |
description: 'full file name to where the download should be output' | |
}) | |
.option('secure', { | |
alias: 's', | |
type: 'boolean', | |
default: false, | |
description: 'when true use https instead of http' | |
}) | |
.parse(); | |
console.log(`> Downloading from ${args.url}`); | |
const tempFile = 'tmp_file'; | |
const file = fs.createWriteStream(tempFile, { emitClose: false, autoClose: false }); | |
const protocol = args.secure ? https : http; | |
const request = protocol | |
.get(args.url, function (response) { | |
if (response.statusCode !== 200) { | |
downloadFailed(`request failed ${response.statusCode}:${response.statusMessage}`); | |
} | |
response.pipe(file); | |
file.on('finish', () => { | |
file.close(); | |
fs.rename(tempFile, args.output, function (error) { | |
if (error) { | |
downloadFailed(error.message); | |
} | |
downloadSucceeded(args.output); | |
}); | |
}); | |
}) | |
.on('error', error => { | |
downloadFailed(error.message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment