Node.js,获取文件的文件类型

问题描述:

已有6年历史的问题" Node.js-文件系统获取文件类型,2012年左右的解决方案"更好的答案,但那时过时的答案才是正确的答案.

The six-year-old question "Node.js - File System get file type, solution around year 2012" has a better answer but the outdated answer was the correct one by then.

提出问题,以获取最新的解决方案.

Hence the question, for an up-to-date solution.

选项1:如果想要模仿类型:

安装

npm i -S file-type read-chunk

使用

const readChunk = require('read-chunk');
const fileType = require('file-type');

const buffer = readChunk.sync(filePath, 0, fileType.minimumBytes);
console.log(fileType(buffer));

选项2:如果您只需要可能的文件扩展名:

安装

npm i -S image-size

使用

const sizeOf = require('image-size');
console.log(sizeOf(filePath).type);