How To Get the MIME Type of a File in Node.js
Tags: beginners, node, npm, tutorial
Published: 2023-02-08 13:58:18

## Introduction

The ability to manage various file types is essential for many applications in this modern world. The MIME type, which specifies a file's format and enables computing systems decide how to handle the file, is one of the most crucial pieces of information when working with files. This article will cover obtaining a file's MIME type using different packages in Node.js.

## What Is a MIME Type?

The file MIME (Multipurpose Internet Mail Extensions) type is a string identifier that specifies the format of a file. Web browsers and servers use it to determine how to handle a file when requesting or uploading a file.

The [IETF's RFC 6838](https://www.rfc-editor.org/rfc/rfc6838) defines and standardizes MIME types. The Internet Assigned Numbers Authority (IANA) manages all official MIME types, and their [Media Types page](https://www.iana.org/assignments/media-types/media-types.xhtml) comprises the most recent and comprehensive list.

## Components of a MIME Type

```jsx
'type/subtype'

//EXAMPLES OF MIME TYPES 
'text/plain'
'image/jpeg'
```

A MIME type only has two parts: a type and a subtype, separated by a slash (/), and does not contain any whitespace.
The type designates the broad category the data type belongs to, such as text or image.
The subtype identifies the precise data that the MIME type represents.

It provides more specific information about the file format. 

For example, the MIME type **`'text/plain'`** specifies that the file is plain text, while **`'image/jpeg'`** determines that the file is a JPEG image.

## The mime package

The package **`mime`** is a lightweight npm package that offers a straightforward method for determining a file's MIME type based on its extension and contents. You run the following npm command in your terminal to install this package:

```bash
npm install mime
```

After installation, you can use the package in your code by requiring it as follows:

```jsx
const mime = require('mime');
```

The **`mime`** package includes a method called **`getType()`** available to determine the MIME type of a file. This method takes a file path or extension as an argument.

For example:

```jsx
const mime = require('mime');
const file_path = 'files\file.txt'
const mime_type = mime.getType(file_path)
console.log(mime_type);
// Output: 'text/plain'
```

## The **mime-types** Package

You can use the popular npm module, **`mime-types`**, to determine the MIME type of a file. To use this package, you need to first install it by running the following **npm** command in your terminal:

```bash
npm install mime-types
```

Once installed, you can use the available method **`lookup()`** to get the file MIME type after requiring it in your code. For example:

```jsx
const mime = require('mime-types');
const filePath = 'files\e6222886fdc2dc2b847284232e03ba74.jpg';
const mimeType = mime.lookup(filePath);
console.log(mimeType); 
// Output: 'image/jpeg'
```

The code block above imports the **`mime-types`** package and uses it to determine the MIME type of a file located at the specified file path. The **`lookup()`** method determines the MIME type based on the file extension. The determined MIME type is then logged to the console. In this case, the file extension is **`.jpeg`**, and the mime type is **`'image/jpeg'`**. Note that the **`lookup()`** method returns **`false`** if the file argument passed is either invalid or not found.

>  **mime-types** package is a heavier module than the **mime** package
> 

## The **file-type** Package

The **`file-type`** package is another popular npm module accessible to get the MIME type of a file. To use this package, install it first by running the following **npm** command in your terminal:

```bash
npm install file-type
```

This package is a [pure ESM (ECMAScript Module) package](https://www.makeuseof.com/javascript-module-systems/), meaning that it is written using the ECMAScript modules syntax and can only be used using the import keyword.

The file-type package detects the MIME type of binary-based file formats such as buffers and [arraybuffers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). It is not suitable for text-based file formats like .csv and .svg. 

It does this by checking the magic number of the buffer, the first few bytes of the file that are unique to each file format. This allows the package to identify the file type without relying on the file extension or other metadata.

For example:

```jsx
import { fileTypeFromFile } from 'file-type';

(async () => {
  const type = await fileTypeFromFile('pexels-photo-265129.jpeg');
  console.log(type);
 
})();
//Output: { ext: 'jpg', mime: 'image/jpeg' }
```

This script uses the **`file-type`** package to determine the file type of a given file by passing the file path as an argument to the **`fileTypeFromFile`** function. The returned value is an object containing the file's extension and MIME type and is logged to the console.

The use of an immediately invoked async arrow function in this script enables the **`await`** keyword to be used within the function's body to wait for the **`fileTypeFromFile`** function to finish before moving on to the following line of code.

## Importance of MIME Types

Identifying MIME types is essential for internet communication, as it allows you to determine the type of data sent and received. You can handle data correctly and avoid security issues such as content-sniffing attacks by comprehending and correctly identifying MIME types.