MIME Type Detector
file-type-mime is a JavaScript utility designed to identify the MIME type and file extension of a given file by analyzing its binary content, typically provided as an `ArrayBuffer`. It is currently at version 0.4.7, indicating a pre-1.0 release. While specific release cadence isn't detailed, pre-1.0 versions often imply that the API might still be subject to minor breaking changes between minor versions as the library matures. This library supports a range of common file types including various image formats (BMP, GIF, JPEG, PNG, HEIC, TIFF), documents (PDF, DOCX, XLSX, PPTX, ODT), and archives (ZIP, GZ, RAR), with an optional `extra` flag to detect generic `json` and `txt` types. Its key differentiators include its lightweight nature and its focus on direct buffer analysis without external dependencies, making it suitable for both Node.js environments and browser-based file upload scenarios where direct file content analysis is required.
Common errors
-
TypeError: parse is not a function
cause Attempting to use `require()` or a default import (`import parse from 'file-type-mime'`) for the `parse` function.fixUse a named import for `parse`: `import { parse } from 'file-type-mime';` -
TypeError: The "buffer" argument must be an instance of ArrayBuffer or a TypedArray. Received an instance of Buffer
cause Passing a Node.js `Buffer` object directly to `parse` instead of its underlying `ArrayBuffer`.fixAccess the `ArrayBuffer` from the Node.js `Buffer` using `.buffer`: `parse(myNodeBuffer.buffer)`. -
Property 'mime' does not exist on type '{ ext: string; mime: string; } | undefined'.cause Not checking if the `parse` function returned `undefined` before attempting to access properties like `mime` or `ext`.fixAdd a null check for the result: `const result = parse(buffer); if (result) { console.log(result.mime); }`
Warnings
- breaking As a pre-1.0.0 package, the API of `file-type-mime` is not yet considered stable. Minor version updates (e.g., 0.4.x to 0.5.x) may introduce breaking changes without a major version increment.
- gotcha The `parse` function exclusively expects an `ArrayBuffer` as its first argument. Passing a Node.js `Buffer` directly will result in a `TypeError` due to API mismatch, as Node.js `Buffer` is a `Uint8Array` but not directly an `ArrayBuffer` instance.
- gotcha By default, the library focuses on common binary file formats. To detect generic text types like `application/json` or `text/plain`, you must explicitly pass `{ extra: true }` in the options object.
- gotcha The library returns `undefined` if the file type cannot be identified based on its internal signatures. This can happen for unsupported file types or corrupted buffers, requiring explicit handling of the `undefined` return.
Install
-
npm install file-type-mime -
yarn add file-type-mime -
pnpm add file-type-mime
Imports
- parse
import parse from 'file-type-mime'; const parse = require('file-type-mime');import { parse } from 'file-type-mime'; - Options
import { Options } from 'file-type-mime';import type { Options } from 'file-type-mime'; - Result
import { Result } from 'file-type-mime';import type { Result } from 'file-type-mime';
Quickstart
import { parse } from "file-type-mime";
import { readFileSync, existsSync } from "node:fs";
import { resolve } from "node:path";
// Create a dummy PDF file for demonstration if it doesn't exist
const dummyFilePath = resolve("./dummy.pdf");
if (!existsSync(dummyFilePath)) {
// In a real scenario, you'd have an actual file. This is just for a runnable example.
// For simplicity, we'll create a minimal valid PDF header.
// This won't be a full PDF, but enough to be detected by some tools.
const dummyPdfContent = Buffer.from('%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 0>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000057 00000 n\ntrailer<</Size 3/Root 1 0 R>>startxref\n106\n%%EOF');
// For actual testing, replace with a real PDF or path to one.
// require('node:fs').writeFileSync(dummyFilePath, dummyPdfContent);
// For this runnable example, we'll just use a direct buffer.
console.log('No dummy.pdf found. Using a synthetic buffer for demonstration.');
}
// Simulate reading a file buffer (replace with actual file path if desired)
const fileBuffer = Buffer.from('%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 0>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000057 00000 n\ntrailer<</Size 3/Root 1 0 R>>startxref\n106\n%%EOF'); // Example PDF header
const result = parse(fileBuffer.buffer); // Pass ArrayBuffer from Node.js Buffer
if (result) {
console.log(`Detected MIME Type: ${result.mime}`);
console.log(`Detected File Extension: ${result.ext}`);
} else {
console.log('Could not detect file type.');
}
// Example with `extra` option for text/plain
const textBuffer = Buffer.from('This is a plain text file.');
const textResult = parse(textBuffer.buffer, { extra: true });
if (textResult) {
console.log(`\nDetected MIME Type (with extra): ${textResult.mime}`);
} else {
console.log('Could not detect text file type with extra option.');
}