Nodejitsu

Save time managing and deploying your node.js app

Nodejitsu has joined GoDaddy

We are excited to join GoDaddy to help spearhead their largest Node.js product: Website Builder. Please read our blog post to learn more about customer transition plans and our continued support for Open Source within the node community.

Want to know all the details?
Read the full blog post or read the GoDaddy Announcement.

npmawesome: determine true mime type with mmmagic

About the author

Name
Location
Worldwide
nodejitsu nodejitsu

Other popular posts

- Scaling Isomorphic Javascript Code - Keep a node.js server up with Forever - Package.json dependencies done right
- npm cheat sheet - 6 Must Have Node.js Modules

This is a guest post from Alex Gorbatchev over at npmawesome.com. Nodejitsu loved what npmawesome.com was doing 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.