mirror of
https://github.com/nadimkobeissi/mkbsd.git
synced 2024-12-22 14:26:48 +00:00
Refactor download_image function to support replacing existing files for NodeJS
This commit is contained in:
parent
2d51a5242e
commit
d4a9423d69
40
mkbsd.js
40
mkbsd.js
@ -1,10 +1,11 @@
|
||||
// Copyright 2024 Nadim Kobeissi
|
||||
// Licensed under the WTFPL License
|
||||
|
||||
const fs = require(`fs`);
|
||||
const path = require(`path`);
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const readline = require('readline');
|
||||
|
||||
async function main() {
|
||||
async function main(replaceExisting) {
|
||||
const url = 'https://storage.googleapis.com/panels-api/data/20240916/media-1a-i-p~s';
|
||||
const delay = (ms) => {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
@ -34,7 +35,7 @@ async function main() {
|
||||
const ext = path.extname(new URL(imageUrl).pathname) || '.jpg';
|
||||
const filename = `${fileIndex}${ext}`;
|
||||
const filePath = path.join(downloadDir, filename);
|
||||
await downloadImage(imageUrl, filePath);
|
||||
await downloadImage(imageUrl, filePath, replaceExisting);
|
||||
console.info(`🖼️ Saved image to ${filePath}`);
|
||||
fileIndex++;
|
||||
await delay(250);
|
||||
@ -45,7 +46,11 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadImage(url, filePath) {
|
||||
async function downloadImage(url, filePath, replaceExisting) {
|
||||
if (!replaceExisting && fs.existsSync(filePath)) {
|
||||
console.info(`⚠️ File ${filePath} already exists. Skipping download.`);
|
||||
return;
|
||||
}
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download image: ${response.statusText}`);
|
||||
@ -69,7 +74,28 @@ function asciiArt() {
|
||||
console.info(`🤑 Starting downloads from your favorite sellout grifter's wallpaper app...`);
|
||||
}
|
||||
|
||||
(() => {
|
||||
function promptUser() {
|
||||
return new Promise((resolve) => {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
rl.question("Files already exist in the 'downloads' directory.\n1. Skip existing files and download new ones.\n2. Replace existing files and download all.\nEnter your choice (1 or 2): ", (answer) => {
|
||||
rl.close();
|
||||
resolve(answer === '2');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
asciiArt();
|
||||
setTimeout(main, 5000);
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
const downloadDir = path.join(__dirname, 'downloads');
|
||||
let replaceExisting = true;
|
||||
if (fs.existsSync(downloadDir) && fs.readdirSync(downloadDir).length > 0) {
|
||||
replaceExisting = await promptUser();
|
||||
}
|
||||
|
||||
await main(replaceExisting);
|
||||
})();
|
||||
|
Loading…
Reference in New Issue
Block a user