Home > Mobile >  Save image locally from url using javascript node.js and fs
Save image locally from url using javascript node.js and fs

Time:10-16

Working on a YuGiOh Discord bot and am trying to save images locally through the url. Let's say I have a .png/.jpg link like here : https://images.ygoprodeck.com/images/cards/98127546.jpg and I want to store it into my projects img folder. How would I do that using Node.js? I also have fs.

CodePudding user response:

Using https and fs core modules in Node, you can pipe the file download into a file in /img with the following code

import fs from 'fs';
import https from 'https';


// download the image and save to /img
let download = function (url, dest, cb) {
    let file = fs.createWriteStream(dest);
    let request = https
        .get(url, function (response) {
            response.pipe(file);
            file.on('finish', function () {
                file.close(cb);
            });
        })
        .on('error', function (err) {
            fs.unlink(dest); // Delete the file async if there is an error
            if (cb) cb(err.message);
        });

    request.on('error', function (err) {
        console.log(err);
    });
};
// use as: download(url, destination, callback)

let url = 'https://images.ygoprodeck.com/images/cards/98127546.jpg';
download(url, 'img/98127546.jpg', function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('done');
    }
});
  • Related