[英]Get MIME type of a file without extension in Node.js
Yes, there is a module called mmmagic .是的,有一个名为mmmagic的模块。 It tries best to guess the MIME of a file by analysing its content.
它尽量通过分析文件的内容来猜测文件的 MIME。
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.但请记住,对 MIME 类型的猜测可能并不总是导致正确答案。
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:另一种可能性是使用 exec 或 execSync 函数在 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.然而,这不是更好的解决方案,因为仅适用于 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
要在 Windows 中运行它,请检查这个超级用户问题: 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.您可以简单地使用
String.prototype.split()
然后取数组的最后一个元素,即类型。
You can take the last element on the array using the pop method:您可以使用 pop 方法获取数组中的最后一个元素:
const mimeType = fileName.split('.').pop()
or或者
const type = mimeType.split('/')
then type[1]
will have the extension然后
type[1]
将具有扩展名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.