sanitize a filename and use the mimetype to get the extension in typescript

index.ts
import { extname } from 'path';

function sanitizeFilename(filename: string): string {
    // Remove unwanted characters from the filename
    return filename.replace(/[^a-z0-9]/gi, '_');
}

function getFileExtensionFromMimetype(mimetype: string): string {
    const extensions: Record<string, string> = {
        'image/jpeg': '.jpg',
        'image/png': '.png',
        'application/pdf': '.pdf',
        // Add more mappings as needed
    };

    // Default extension if mimetype is not found
    const defaultExtension = '.dat';

    return extensions[mimetype] || defaultExtension;
}

// Example usage
const filename = 'my picture.jpeg';
const sanitizedFilename = sanitizeFilename(filename);
const mimetype = 'image/jpeg';
const fileExtension = getFileExtensionFromMimetype(mimetype);

console.log(`Sanitized Filename: ${sanitizedFilename}`); // Output: my_picture.jpeg
console.log(`File Extension: ${fileExtension}`); // Output: .jpg
941 chars
30 lines

gistlibby LogSnag