'Get file extention using only file name in javascript

I am creating a discord bot (irrelevent) that sends images into the chat. The user can type out the name of the image without needing to type the file extention. The problem is that the bot doesn't know what the file extention is so it will crash if the picture is a .jpg and the program was expecting a .png. Is there a way to make the program not require a file extention to open the file?

let image = imageName;
message.channel.send({ files: [`media/stickers/${imageName}.png`] });


Solution 1:[1]

Using fs - specifically the Promise version of fs, makes this quite simple

import { readdir } from 'fs/promises';


const getFullname = async (path, target)  => 
    (await readdir(path))
    .find(file => 
        file === target || file.split('.').slice(0,-1).join('.') === target
    );
try {
    const actualName = await getExtension('media/stickers', imageName);
    if (!actualName) {
        throw `File ${imageName} not found`;
    }
    message.channel.send({ files: [`media/stickers/${actualName}`] });
} catch(error) {
    // handle your errors here
}

You can pass in the name with or without the extension and it will be found - note, this is NOT case insensitive ... so XYZ won't match xyz.jpg - easily changed if you need case insensitivity

Solution 2:[2]

There are only a few known image extensions like jpg, png, gif, jpeg. Maybe try and fetch the file with best guess extension, if it throws exception try the next format.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bravo
Solution 2 earthdomain