Get MIME file type without extension in Node.js

Considering I have a file with no extension appended to its name, ex: images/cat_photo

Is there a method in Node.js to retrieve the MIME type of a given file? The mime module does not work in this case.

+4


source to share


2 answers


Yes, there is a module called mmmagic . It is best at guessing the MIME of a file by analyzing its contents.

The code will look like this (taken from the 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 guessing the MIME type may not always lead to the correct answer.

Be sure to check the types of signatures on the page.

+2


source


You can just use String.prototype.split()

and then take the last element of the array to be the type.

You can grab the last element in the array using the pop method:

const mimeType = fileName.split('.').pop()

      



or

const type = mimeType.split('/')

      

then type[1]

will have an extension

0


source







All Articles