From 074bcf20d7a2c7f08554e410d1e8e1eb6f9490c4 Mon Sep 17 00:00:00 2001 From: Quentin Roussel Date: Sun, 18 Aug 2024 13:48:56 +0800 Subject: [PATCH] make sure that init downloads exactly the last `count` available images --- downloader.mjs | 13 +++++++++---- index.mjs | 6 ++++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/downloader.mjs b/downloader.mjs index d9a00f8..bbacef0 100644 --- a/downloader.mjs +++ b/downloader.mjs @@ -62,21 +62,26 @@ function downloadImage(time_string, filepath) { export async function initImages(count) { let files = fs.readdirSync('images/'); - for (let i = count; i >= 0; i--) { + let downloaded = 0; + let i = 0; + while(downloaded < count) { let time_string = getTimeString(i); let filename = `images/${time_string}.png`; if (files.includes(`${time_string}.png`)) { + downloaded++; + i++; continue; } try { - await downloadImage(time_string, filename) + await downloadImage(time_string, filename); + downloaded++; } catch (error) { //Response 302, we've reached the latest available image if (error.message === '302') { - console.log('Could not download image after ' + time_string); - return; + console.log('Could not download image ' + time_string); } } + i++; } } diff --git a/index.mjs b/index.mjs index d9838d5..a40cf7f 100644 --- a/index.mjs +++ b/index.mjs @@ -1,11 +1,13 @@ import { initImages, updateImages } from './downloader.mjs'; -initImages(10).then(() => { +const IMAGE_COUNT = 5; + +initImages(IMAGE_COUNT).then(() => { console.log('Downloaded initial images successfully'); }); setInterval(() => { - updateImages(10).then(() => { + updateImages(IMAGE_COUNT).then(() => { console.log('Updated images successfully'); }); }, 5 * 60 * 1000);