1const request = require('request');
2const fs = require('fs');
3
4async function download(url, dest) {
5
6 /* Create an empty file where we can save data */
7 const file = fs.createWriteStream(dest);
8
9 /* Using Promises so that we can use the ASYNC AWAIT syntax */
10 await new Promise((resolve, reject) => {
11 request({
12 /* Here you should specify the exact link to the file you are trying to download */
13 uri: url,
14 gzip: true,
15 })
16 .pipe(file)
17 .on('finish', async () => {
18 console.log(`The file is finished downloading.`);
19 resolve();
20 })
21 .on('error', (error) => {
22 reject(error);
23 });
24 })
25 .catch((error) => {
26 console.log(`Something happened: ${error}`);
27 });
28}
29
30// example
31
32(async () => {
33 const data = await download('https://random.dog/vh7i79y2qhhy.jpg', './images/image.jpg');
34 console.log(data); // The file is finished downloading.
35})();
1var fs = require('fs'),
2 request = require('request');
3
4var download = function(uri, filename, callback){
5 request.head(uri, function(err, res, body){
6 console.log('content-type:', res.headers['content-type']);
7 console.log('content-length:', res.headers['content-length']);
8
9 request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
10 });
11};
12
13download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
14 console.log('done');
15});