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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With