/node-mgc

Node libmagic addon (detects mime info by inspecting node buffer's data).

Overview

This addon adds to node functionality of libmagic and `file` util.

Unlike to https://github.com/mscdex/mmmagic it:

  • Uses native installed libmagic
  • Support strings, node buffers and streams only
  • Operate absolutely thread-safe (although libmagic isn’t thread-safe)

Usage

var MGC = require('mgc'); /* require module */
var mgc = new MGC(flags); /* create new instance with flags (optional) */

Loading

Default database

mgc.load(function(err){ /* load default .mgc databases */
  if(err) throw err;
  /* now mgc is ready for use */
});

Own .mgc databases

mgc.load('/usr/share/file/magic.mgc:/home/user/magic.mgc',
function(err){ /* load .mgc databases */
  if(err) throw err;
  /* now mgc is ready for use */
});

Detecting

String and Buffer

mgc.data(buf_or_str, function(err, desc){ /* gets description of data */
  if(err) throw err;
  console.log(desc);
});

Readable Stream

var FS = require('fs');
var stm = FS.createReadStream('path/to/file');
mgc.wrap(stm);
stm.on('magic', function(err, desc){ /* gets description of data */
  if(err) throw err;
  console.log(desc);
});

Specs

Flags

Flags is a string of names, like this:

  • debug, d — turn on debugging
  • type, t — return the MIME type
  • enc, c — return the MIME encoding
  • mime, m — return the MIME type and encoding (same as t+c)
  • all, a — return all matches
  • error, e — handle ENOENT etc as real errors

Flags may be combined in any order and separated by +|,:

Wrap

You can pass a minimal (for detecting) content length in bytes as second argument to wrap call. By default it equals to 16 Kbytes.