/

How to Retrieve the File Extension in Node.js from the MIME Type

How to Retrieve the File Extension in Node.js from the MIME Type

When working with file uploads in Node.js, you may encounter situations where you need to extract the file extension from the MIME type. In this article, we’ll explore two methods you can use to achieve this.

Method 1: Parsing the File Name

One way to retrieve the file extension is by parsing the file name. You can accomplish this with the built-in path module in Node.js. Here’s an example of how you can use it:

1
2
const path = require('path');
const fileExtension = path.extname(req.files.logo.name); // Returns the file extension

This method does not require any additional third-party libraries and is quite straightforward to implement.

Method 2: Using the mime-types Package

Alternatively, you can utilize the popular mime-types package to retrieve the file extension based on the MIME type. This method can be beneficial if you’re already working with MIME types and want a more comprehensive solution. Here’s an example:

1
2
3
const mime = require('mime-types');
const mimeType = 'image/png'; // Example MIME type
const fileExtension = mime.extension(mimeType); // Returns the file extension

By passing the MIME type to the extension() function, you can obtain the associated file extension. The mime-types package provides an extensive list of MIME types and their corresponding extensions.

In conclusion, whether you prefer parsing the file name or utilizing the mime-types package, both methods allow you to retrieve the file extension from the MIME type in Node.js. Choose the approach that best fits your requirements and coding style.