Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 295
Amanda Merla Avatar asked Aug 05 '14 07:08

Amanda Merla


People also ask

How do I find MIME type?

For detecting MIME-types, use the aptly named "mimetype" command. It has a number of options for formatting the output, it even has an option for backward compatibility to "file". But most of all, it accepts input not only as file, but also via stdin/pipe, so you can avoid temporary files when processing streams.

How do I find the file type in node JS?

To get the file extension in a Node. js application, you can use the extname() method from the path built-in module. The extname() method returns the given path extension from the last occurrence of the . (period) character to the end of the string in the last part of the path.

Is MIME type same as extension?

Whereas file extensions are commonly used for your OS to decide what program to open a file with, Mime types are used by your browser to decide how to present some data (or the server on how to interpret received data). Both are optional but it's a good practice to have an agreement.

Where is MIME type stored in a file?

All MIME type information is stored in a database. The MIME database is located in the directory /usr/share/mime/ . The MIME database contains a large number of common MIME types, stored in the file /usr/share/mime/packages/freedesktop. org.


1 Answers

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.

like image 114
alandarev Avatar answered Oct 31 '22 17:10

alandarev