ds.xowos
ds.xowos

Reputation: 81

employ good habits in nodejs

How can I replace the * if and else if * in the code to make it more readable, in my real code I have more than 30 else ifs, to detect different types of file extensions and it doesn't look right

//get a message
client.on('message', async message => {
    //detect message with files
    if(message.hasMedia){
        //save file in variable
        let attachmentData = await message.downloadMedia();

        //know its type of extension
        //this is what i want to improve
        var extension = "";
        if (attachmentData.mimetype == "image/jpeg") 
            extension = "jpg";
        else if (attachmentData.mimetype == "image/png") 
            extension = "png";
        else if (attachmentData.mimetype == "image/gif") 
            extension = "gif";
        else if (attachmentData.mimetype == "application/vnd.openxmlformats-officedocument.presentationml.presentation")
            extension = "pptx"
        if (extension == "")
            return;

        //convert the file to download
        var base64Data = attachmentData.data.replace(/^data:image\/png;base64,/, "");
    }
})

Upvotes: 0

Views: 41

Answers (1)

ray
ray

Reputation: 27245

Create a mapping of mime type to extension and do a lookup:

const extensions = {
  'image/jpeg': 'jpg',
  'image/png': 'png',
  // etc
}

And then do a lookup:

const extension = extensions[attachmentData.mimetype];

There are libraries like mime-types that will do this for you.

Upvotes: 3

Related Questions