Get MIME type of a file without extension in Node.js
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.
Another possibility is to use exec or execSync function to run the 'file' command on Linux SO:
/**
* Get the file mime type from path. No extension required.
* @param filePath Path to the file
*/
function getMimeFromPath(filePath) {
const execSync = require('child_process').execSync;
const mimeType = execSync('file --mime-type -b "' + filePath + '"').toString();
return mimeType.trim();
}
However is not the better solution since only works in Linux. For running this in Windows check this Superuser question: https://superuser.com/questions/272338/what-is-the-equivalent-to-the-linux-file-command-for-windows
Greetings.