Usually when we want to check the type for a file that we have to upload we look for its MIME type in the file object.
But.. What if the file for some reasons doesn't has an extension or have a wrong extension assigned? 🤔
Luckily the magic numbers come to our aid.
Magic numbers are a byte pattern inside a file that is used to determine which is the type of the file.
Or, more properly, from Wikipedia:
Magic numbers implement strongly typed data and are a form of in-band signaling to the controlling program that reads the data type(s) at program run-time. Many files have such constants that identify the contained data
I want instead focus on the file-type library. This library applies the magic numbers approach to the ArrayBuffer of the file for detecting its type. It works with a large amount of different file types.
Unfortunately some file types, especially plain-text files, are harder to spot by this method and if you want to check the type you have to use a parser for every kind of file you have to consider.
For example if you want to spot SVG you can use is-svg library from NPM.
I've created a Sandbox that use the file-type library which you can play around 👇
👋 See you in the next article!