{"size": 1294, "ext": "js", "max_stars_repo_path": "geekhack-scraper/downloadImage.js", "max_stars_repo_name": "Gobluebro/Geekhack-scraper", "max_stars_repo_stars_event_min_datetime": "2019-02-09T17:16:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T22:08:11.000Z", "max_issues_repo_path": "geekhack-scraper/downloadImage.js", "max_issues_repo_name": "Gobluebro/Geekhack-scraper", "max_issues_repo_issues_event_min_datetime": "2020-02-24T03:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T13:39:24.000Z", "max_forks_repo_path": "geekhack-scraper/downloadImage.js", "max_forks_repo_name": "Gobluebro/Geekhack-scraper", "max_forks_repo_forks_event_min_datetime": "2021-12-09T15:32:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T15:32:42.000Z"}
{"max_stars_count": 4, "max_issues_count": 15, "max_forks_count": 1, "avg_line_length": 30.0930232558, "max_line_length": 122, "alphanum_fraction": 0.5680061824}
// replace with https://github.com/hgouveia/node-downloader-helper
const download = require("@jinphen/download2");
const fs = require("fs");

module.exports = async (imageToDowload) => {
  let orderNumber = imageToDowload.orderNumber;
  let url = imageToDowload.url;
  let thread_id = imageToDowload.thread_id;

  let path = process.env.IMAGES_PATH + `/${thread_id}`;
  // I love this download module. It does all the work for me and allows me to save images I had trouble with in the past.
  let image = download(url, path)
    .then(({ data, filename }) => {
      if (!fs.existsSync(path + `/${filename}`)) {
        console.log(filename + " image already saved");
      } else {
        fs.writeFileSync(path + `/${filename}`, data);
        console.log(
          "thread: " +
            thread_id +
            " filename: " +
            filename +
            " saved to " +
            path
        );
        let downloadedImage = {
          thread_id: thread_id,
          name: filename,
          url: url,
          order_number: orderNumber,
        };
        return downloadedImage;
      }
    })
    .catch((err) => {
      console.log(
        "failed to download at " + url + " on thread number " + thread_id
      );
      console.error(err);
    });
  return image;
};
