Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Detecting File Type in Node and Browser

| Comments

Detecting a file type is pretty easy, it's all about knowing the File Signatures aka "magic numbers"! of the file.

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

Normally on CLI one would use file command to determine file type. For example:

1
2
3
$ file meow.ogg

Ogg data, Vorbis audio, stereo, 44100 Hz, ~64000 bps, created by: Xiph.Org libVorbis I (1.1.0 RC1)

The mime type detection will file would be like:

1
2
3
$ file --mime-type -b ~/labs/npm/is-ogg/fixture.ogg

application/ogg

One could easily do a npm install mime mime

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

Or install

1
2
3
4
5
6
7
 var mmm = require('mmmagic'),
      Magic = mmm.Magic;
  var magic = new Magic(mmm.MAGIC_MIME);
  magic.detectFile('meow.ogg', function(err, result) {
      if (err) throw err;
      console.log(result);
  });

But would not it be fun to have a simple module that could read buffer as well as Buffer/Uint8Array ?

Well, here it is file-type detects the file type of a Buffer/Uint8Array!

P.R are welcome to that project and /me contributed audio-type to it.

So the logic behind is to read the required bytes using read-chunk and check for the required bytes, for example have a look at is-ogg.

The project is nicely aligned with the Unix Philosophy of doing one thing and doing it in the best way, each of the file types are broken down in the individual modules like:

And it also has a nice little CLI util as well:

1
$ npm install --global file-type
1
2
3
4
5
6
7
8
9
$ file-type --help

Usage
  $ cat <filename> | file-type
  $ file-type <filename>

Example
  $ cat unicorn.png | file-type
  png

Do feel free to send new suggestion/PR to this project and hope this helped you!

Comments