Reputation: 22984
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.
Upvotes: 4
Views: 9111
Reputation: 39005
OPTION 1: If you want the mimetype:
Install
npm i -S file-type read-chunk
Use
const readChunk = require('read-chunk');
const fileType = require('file-type');
const buffer = readChunk.sync(filePath, 0, fileType.minimumBytes);
console.log(fileType(buffer));
OPTION 2: If you just need the would-be file extension:
Install
npm i -S image-size
Use
const sizeOf = require('image-size');
console.log(sizeOf(filePath).type);
Upvotes: 2