Skip to content

Commit

Permalink
✨ feat(saveImageFromUrl): Dynamic Extension Handling (danny-avila#1514)
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
danny-avila committed Jan 7, 2024
1 parent 73b42a6 commit 6145f7a
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions app/clients/tools/saveImageFromUrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 6145f7a

Please sign in to comment.