fs from download link code example
Example 1: download image in nodejs
const request = require('request');
const fs = require('fs');
async function download(url, dest) {
const file = fs.createWriteStream(dest);
await new Promise((resolve, reject) => {
request({
uri: url,
gzip: true,
})
.pipe(file)
.on('finish', async () => {
console.log(`The file is finished downloading.`);
resolve();
})
.on('error', (error) => {
reject(error);
});
})
.catch((error) => {
console.log(`Something happened: ${error}`);
});
}
(async () => {
const data = await download('https://random.dog/vh7i79y2qhhy.jpg', './images/image.jpg');
console.log(data);
})();
Example 2: node js download file to folder
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
}).on('error', function(err) {
fs.unlink(dest);
if (cb) cb(err.message);
});
};