Last active
August 10, 2021 09:30
-
-
Save kraklin/50d90d89ff6f45d005b7229179e859fb to your computer and use it in GitHub Desktop.
Test the cURL download from JS script
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 fs = require('fs'); | |
const { spawn } = require('child_process'); | |
const path = require('path'); | |
const download_file = (file_url) => { | |
// create url and filename variables | |
const url = new URL(file_url); | |
const fileName = url.pathname.split('/').pop(); | |
const savedFilePath = path.join(__dirname, fileName); | |
// create an instance of writable stream | |
const file = fs.createWriteStream(savedFilePath); | |
// execute curl using child_process' spawn function | |
const curl = spawn('curl', ['-#fL', url.toString()]); | |
// add a 'data' event listener for the spawn instance | |
curl.stdout.on('data', function(data) { file.write(data); }); | |
// add an 'end' event listener to close the writeable stream | |
curl.stdout.on('end', function(data) { | |
file.end(); | |
console.log('File from:\n\x1b[33m' + url.toString() + '\n\x1b[0mhas been downloaded to\n\x1b[33m' + savedFilePath+'\x1b[0m'); | |
}); | |
// when the spawn child process exits, check if there were any errors and close the writeable stream | |
curl.on('exit', function(code) { | |
if (code != 0) { | |
console.log('Failed: ' + code); | |
} | |
}); | |
}; | |
download_file("https://github.com/elm/compiler/releases/download/0.19.1/binary-for-linux-64-bit.gz"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment