在nodejs中养成良好的习惯

employ good habits in nodejs

如何替换代码中的 * if 和 else if * 以使其更具可读性,在我的真实代码中我有 30 多个 else if,用于检测不同类型的文件扩展名并且它看起来不对

//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,/, "");
    }
})

创建 mime 类型到扩展名的映射并进行查找:

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

然后进行查找:

const extension = extensions[attachmentData.mimetype];

有像 mime-types 这样的图书馆可以为您做这件事。