Download Remote Files Using Node

Here is a simple code snippet to help you use node to download a remote file URL to your computer

const http = require('http');
const fs = require('fs');
const url = 'https://path/to/remote/data.js';
const path = 'data.js';


/**
 *
 * @param {string} url The URL location of the file you wish to download
 * @param {string} destination The path to which you wish to write the content of the remote file.
 * @param {function} success A success callback
 * @param {function} error An error callback
 */
const download = (url, destination, success, error) => {
	var file = fs.createWriteStream(destination);
	var request = http.get(url, function (response) {
		response.pipe(file);
		file.on('finish', function () {
			file.close(function () {
				typeof success == 'function' && success.apply(null, [destination]);
			}); 
		});
	}).on('error', function (err) { 
		fs.unlink(destination); // Delete file is error
		typeof error == 'function' && error.apply(null, [err.message]);
	});
};


download(url, path, function (location) {
	console.log(location);
}, function (err) {
	console.log(err);
});