feat(saveImageFromUrl): Dynamic Extension Handling (#1514)

- Enhanced the `saveImageFromUrl` function to dynamically handle file extensions based on the content type of the fetched image.
- Replaced the method of appending a '.png' extension with a more robust approach using regular expressions and the path module.
- Allows for correct extension replacement or addition, ensuring filename consistency and compatibility with the actual image format.
- Prevents issues with double extensions (e.g., 'someimage.jpg.png') and aligns saved file types with their respective content types.
This commit is contained in:
Danny Avila 2024-01-07 15:22:33 -05:00 committed by GitHub
parent 050a92b318
commit c9aaf502af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -11,18 +11,24 @@ async function saveImageFromUrl(url, outputPath, outputFilename) {
responseType: 'stream',
});
// Get the content type from the response headers
const contentType = response.headers['content-type'];
let extension = contentType.split('/').pop();
// Check if the output directory exists, if not, create it
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true });
}
// Ensure the output filename has a '.png' extension
const filenameWithPngExt = outputFilename.endsWith('.png')
? outputFilename
: `${outputFilename}.png`;
// Replace or append the correct extension
const extRegExp = new RegExp(path.extname(outputFilename) + '$');
outputFilename = outputFilename.replace(extRegExp, `.${extension}`);
if (!path.extname(outputFilename)) {
outputFilename += `.${extension}`;
}
// Create a writable stream for the output path
const outputFilePath = path.join(outputPath, filenameWithPngExt);
const outputFilePath = path.join(outputPath, outputFilename);
const writer = fs.createWriteStream(outputFilePath);
// Pipe the response data to the output file