This post was written for Nodejitsu blog and is crossposted here. Nodejitsu loved what I was doing at npmawesome.com and is now supporting the project.

mmmagic (GitHub: mscdex/mmmagic, License: MIT) by Brian White is an async libmagic binding for Node.js for detecting content types by actually doing data inspection and not just trusting a file extension. Obviously this is a much slower method, but when you really want to be sure and get the right file type, mmmagic is just the tool you need.

npm install mmmagic

Usage

In the example below I’m checking a type of the same JPEG file, one with jpg extension, another with png extension. In both cases the result is the same image/jpeg.

var mmmagic = require('mmmagic');
var magic = new mmmagic.Magic(mmmagic.MAGIC_MIME_TYPE);

magic.detectFile('./kitten.jpg', function(err, result) {
  if (err) throw err;

  // image/jpeg
  console.log('kitten.jpg', result);
});

magic.detectFile('./kitten.png', function(err, result) {
  if (err) throw err;

  // also `image/jpeg` even though extension is PNG
  console.log('kitten.png', result);
});

What Else?

Since mmmagic wraps a native library, it unfortunately can not be used in the browser.

Another thing is absolutely worth mentioning is that Brian White is a prolific JavaScript developer with plenty of modules under his belt many of which I plan to highlight in the near future. Brian White by all measures could be considered a rock star of Node.js and open source in general.

Checkout the runnable example and github example repository.