Hemanth's Scribes

node

Detecting File Type in Node and Browser

Author Photo

Hemanth HM

Thumbnail

Detecting a file type is all about knowing the File Signatures aka “magic numbers”!

Magic numbers are bytes within a file used to identify the format - generally a short sequence of bytes (most are 2-4 bytes long) placed at the beginning of the file.

CLI Method

$ file meow.ogg
Ogg data, Vorbis audio, stereo, 44100 Hz, ~64000 bps

$ file --mime-type -b meow.ogg
application/ogg

Node.js Methods

Using mime:

require('mime').lookup("meow.ogg").split("/")[1]
// 'ogg'

Better Approach: file-type

file-type detects file type from Buffer/Uint8Array by reading magic numbers.

The project follows Unix Philosophy - doing one thing well. Each file type has its own module:

I contributed audio-type to this ecosystem!

#node#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.