4

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.

xpt
  • 20,363
  • 37
  • 127
  • 216

1 Answers1

1

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);
Stephen Paul
  • 37,253
  • 15
  • 92
  • 74
  • 1
    *file-type* doesn't work. just tried and it correctly returns `mime":"application/x-msdownload"` for windows dll, but it returns `undefined` for binaries, on which the `file` command correctly returns `ELF 64-bit LSB shared object, x86-64...` – v.oddou May 30 '19 at 09:52
  • 1
    I tried this solution (both Option 1 and 2) for a file of type txt and it just returned _undefined_ . – nitarshs Jun 26 '19 at 08:41
  • Text files don't need to have a header, hence you cannot determine the type by using methods which use file headers. – Orion Cygnus Apr 28 '20 at 17:49