Search code examples
javascriptnode.jsmime-types

Get MIME type of a file without extension in Node.js


Given I have a file without extension appended to its name, ex: images/cat_photo

Is there a method in Node.js to extract MIME type of a given file? Module mime in this case does not work.


Solution

  • Yes, there is a module called mmmagic. It tries best to guess the MIME of a file by analysing its content.

    The code will look like this (taken from example):

    var mmm = require('mmmagic'),
    var magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);
    
    magic.detectFile('node_modules/mmmagic/build/Release/magic.node', function(err, result) {
        if (err) throw err;
        console.log(result);
    });
    

    But keep in mind, that the guessing of a MIME type may not always lead to right answer.

    Feel free to read up on types signatures on a wiki page.