|
const axios = require('axios'); |
|
const fs = require('fs'); |
|
const path = require('path'); |
|
|
|
async function saveImageFromUrl(url, outputPath, outputFilename) { |
|
try { |
|
|
|
const response = await axios({ |
|
url, |
|
responseType: 'stream', |
|
}); |
|
|
|
|
|
if (!fs.existsSync(outputPath)) { |
|
fs.mkdirSync(outputPath, { recursive: true }); |
|
} |
|
|
|
|
|
const filenameWithPngExt = outputFilename.endsWith('.png') |
|
? outputFilename |
|
: `${outputFilename}.png`; |
|
|
|
|
|
const outputFilePath = path.join(outputPath, filenameWithPngExt); |
|
const writer = fs.createWriteStream(outputFilePath); |
|
|
|
|
|
response.data.pipe(writer); |
|
|
|
return new Promise((resolve, reject) => { |
|
writer.on('finish', resolve); |
|
writer.on('error', reject); |
|
}); |
|
} catch (error) { |
|
console.error('Error while saving the image:', error); |
|
} |
|
} |
|
|
|
module.exports = saveImageFromUrl; |
|
|