![](/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.