![](/img/trans.png)
[英]How to get MIME type of a text file without extension in Node.js
[英]Get MIME type of a file without extension in Node.js
是的,有一个名为mmmagic的模块。 它尽量通过分析文件的内容来猜测文件的 MIME。
代码将如下所示(取自示例):
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);
});
但请记住,对 MIME 类型的猜测可能并不总是导致正确答案。
随意阅读维基页面上的类型签名。
另一种可能性是使用 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();
}
然而,这不是更好的解决方案,因为仅适用于 Linux。 要在 Windows 中运行它,请检查这个超级用户问题: https : //superuser.com/questions/272338/what-is-the-equivalent-to-the-linux-file-command-for-windows
你好。
您可以简单地使用String.prototype.split()
然后取数组的最后一个元素,即类型。
您可以使用 pop 方法获取数组中的最后一个元素:
const mimeType = fileName.split('.').pop()
或者
const type = mimeType.split('/')
然后type[1]
将具有扩展名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.