Guess my Mime type ! (with Typescript)

Damien
2 min readFeb 21, 2024

--

Recently, on a project, I faced an unexpected issue 😯.

Indeed, after some discussions, we decided to store some specific files directly in base64 in our database (I know, this is not the best solution, but that’s not the topic).

From this solution, I updated the API and the model to take into account this new entry, an array of strings (representing my specific files).

Everything went fine until… I saw that these files would be sent to an external service and the extension of each file is required!

Oh god, I didn’t want to update my API and my model just to specify the type of each file… I found this solution a bit dirty. So I started to search for a way to get this extension without any updates, and I finally got it! 🚀

file-type package

For the demonstration, I will use the Next.js framework.
First, install the package: npm install file-type.

A small clarification: this can only be used on the server side.

import { fileTypeFromBuffer } from "file-type";

const base64File = 'your-file-encoded-in-base-64';
const buffer = Buffer.from(base64File, "base64");
const fileTypeMetaData = await fileTypeFromBuffer(buffer);

// fileTypeMetaData?.ext contains the extension like pdf, png, ...
// fileTypeMetaData?.mime contains the mime type like image/jpeg, ...

Et voilà ! But be careful, this is not magic. If your file is corrupted, wrongly formatted, or its type is just unknown to this library, you will have to consider another solution!

Encountered problem

You may encounter the following issue:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: {project-path}/node_modules/file-type/index.js
require() of ES modules is not supported.

There are multiple solutions. In my case, I tested the following one: downgrading the package version with npm install file-type@16.5.3.
If you choose this one, you will have to rename fileTypeFromBuffer to fromBuffer.

Alternatively, here you can find an explanation and two other ways to resolve the issue.

Hope it was helpful! See you around 😄.

--

--