Ama*_*rla 9 javascript node.js mime-types
鉴于我有一个没有附加扩展名的文件,例如: images/cat_photo
Node.js 中是否有一种方法可以提取给定文件的 MIME 类型?在这种情况下,模块mime不起作用。
是的,有一个名为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);
});
Run Code Online (Sandbox Code Playgroud)
但请记住,对 MIME 类型的猜测可能并不总是导致正确答案。
随意阅读维基页面上的类型签名。
另一种可能性是使用 exec 或 execSync 函数在 Linux 上运行“file”命令:
/**
* 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();
}
Run Code Online (Sandbox Code Playgroud)
但这并不是最好的解决方案,因为仅适用于 Linux。要在 Windows 中运行此命令,请检查此超级用户问题: https://superuser.com/questions/272338/what-is-the-equivalent-to-the-linux-file-command-for-windows
问候。