简体   繁体   中英

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.

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.

You could simply use String.prototype.split() and then take the last element of the array which will be the type.

You can take the last element on the array using the pop method:

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

or

const type = mimeType.split('/')

then type[1] will have the extension

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM