Use File Content to Determine MIME Type with Node JS

file, javascript, mime-types, node.js

Solution

That indeed feels like a pity, that most popular MIME modules are just mapping extension to the type.

After searching deeper, I found the module called mmmagic, it seems to be doing exactly what you want.

Be aware, that from working with MIME I was left with a taste, that MIME detection is in principle not completely reliable, and there is a rare chance of false detections.

Example of usage (taken from their site):

  var mmm = require('mmmagic'),
      Magic = mmm.Magic;

  var magic = new Magic(mmm.MAGIC_MIME_TYPE);
  magic.detectFile('node_modules/mmmagic/build/Release/magic.node', function(err, result) {
      if (err) throw err;
      console.log(result);
      // output on Windows with 32-bit node:
      //    application/x-dosexec
  });

Problem

It seems all of the popular MIME type libraries for node.js just use the file name extension rather than peeking into the file to determine the MIME type. Is there a good way to use Node to jump into the file and intelligently determine the file's MIME type in case an extension is not present?

Original source