updated image downloader to accept 3XX codes

This commit is contained in:
Quentin Roussel
2024-08-18 01:49:57 +08:00
parent 16851517ef
commit dd146e5490

View File

@@ -28,24 +28,28 @@ function downloadImage(time_string, filepath) {
} }
client.get(options, (res) => { client.get(options, (res) => {
console.log(`Downloading ${time_string}`); console.log(`Downloading ${time_string}`);
if (res.statusCode === 200) { if (res.statusCode >= 200 && res.statusCode < 400) {
res.pipe(fs.createWriteStream(filepath)) res.pipe(fs.createWriteStream(filepath))
.on('error', reject) .on('error', reject)
.once('close', () => resolve(filepath)); .once('close', () => resolve(filepath));
} else { } else {
// Consume response data to free up memory // Consume response data to free up memory
console.log(`Failed to download ${time_string} with status code ${res.statusCode}`);
res.resume(); res.resume();
reject(new Error(res.statusCode)); reject(new Error(res.statusCode));
} }
}); });
}); });
} }
export async function initImages(count) { export async function initImages(count) {
let files = fs.readdirSync('images/');
for (let i = count; i >= 0; i--) { for (let i = count; i >= 0; i--) {
let time_string = getTimeString(i); let time_string = getTimeString(i);
let filename = `images/${time_string}.png`; let filename = `images/${time_string}.png`;
if (files.includes(`${time_string}.png`)) {
continue;
}
try { try {
await downloadImage(time_string, filename) await downloadImage(time_string, filename)
} catch (error) { } catch (error) {