---
title: "Detecting File Type in Node and Browser"
description: "Using magic numbers and file signatures to detect file types in JavaScript. Practical notes and code examples on Detecting."
url: "https://h3manth.com/scribe/detecting-file-type-in-node-and-browser/"
canonical_url: "https://h3manth.com/scribe/detecting-file-type-in-node-and-browser/"
markdown_url: "https://h3manth.com/scribe/blog/detecting-file-type-in-node-and-browser.md"
publishDate: "2014-05-01T00:00:00.000Z"
author: "Hemanth HM"
category: "node"
tags: ["node","javascript"]
word_count: 129
reading_time_minutes: 1
x_markdown_tokens: 390
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Detecting File Type in Node and Browser

> Using magic numbers and file signatures to detect file types in JavaScript. Practical notes and code examples on Detecting.

Detecting a file type is all about knowing the [File Signatures](https://en.wikipedia.org/wiki/List_of_file_signatures) aka "magic numbers"!

Magic numbers are bytes within a file used to identify the format - generally a short sequence of bytes (most are 2-4 bytes long) placed at the beginning of the file.

## CLI Method

```bash
$ file meow.ogg
Ogg data, Vorbis audio, stereo, 44100 Hz, ~64000 bps

$ file --mime-type -b meow.ogg
application/ogg
```

## Node.js Methods

Using [mime](https://www.npmjs.org/package/mime):

```javascript
require('mime').lookup("meow.ogg").split("/")[1]
// 'ogg'
```

## Better Approach: file-type

[file-type](https://github.com/sindresorhus/file-type) detects file type from Buffer/Uint8Array by reading magic numbers.

The project follows Unix Philosophy - doing one thing well. Each file type has its own module:

- [is-png](https://github.com/sindresorhus/is-png)
- [is-jpg](https://github.com/sindresorhus/is-jpg)
- [is-gif](https://github.com/sindresorhus/is-gif)
- [is-mp3](https://github.com/hemanth/is-mp3)
- [is-ogg](https://github.com/hemanth/is-ogg)
- And many more...

I contributed [audio-type](https://github.com/sindresorhus/audio-type) to this ecosystem!
