Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
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`] });
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Unfortunately, the extension of the filename is required. You know file.mp4 and file.mp3 is entirely different.

However, you can use a try-except and a for loop to get the correct file!

I would suggest:

let image = imageName;
let extensions = [".png", ".jpg", "gif"] // All the extensions you can think of 
const pass = () => {}
for (const extension of extensions) {
  try {
     message.channel.send({ files: [`media/stickers/${imageName}${extension}`] }); // successfully get file and send
     break
  } catch(error) {
     pass() // do nothing, and go back to the loop and test other extension
  }
}

I haven't tried that before, and I am a Python programmer. But I hope you get the idea.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda