隐藏文件扩展名时识别文件类型

Identify File Type When File Extensions Are Hidden

识别任何给定文件类型的正确方法是什么?

只要启用了显示文件扩展名的选项,我知道有几种方法可以做到这一点,它们实际上彼此相同。

path.substring(path.lastIndexOf('.')+1)

const path = require('path')
path.extname(string)

但是如果有人禁用了显示文件扩展名的选项怎么办。在这种情况下,最好以跨平台的方式,我如何识别任何给定文件的文件类型?

也许有更好的方法,但我只能想到这个解决方案。

const { execSync } = require('child_process');

let output = execSync('file ~/textFile')
  .toString()

console.log(output) // will print '/Users/macabeus/textFile: ASCII text'

这仅适用于 Unix 系统,因此您需要在 Windows 中使用 WSL。

当你说 "type" 时,我假设你的意思是 "the portion of the file's name after the last dot" -- 无论用户的 Windows Explorer 设置如何,它都会出现。