Skip to content

Detect the file type of a Buffer/Uint8Array

License

Notifications You must be signed in to change notification settings

mmpro/file-type

 
 

Repository files navigation

ATTENTION: DO NOT USE THIS PACKAGE! Please use https://github.com/sindresorhus/file-type#readme

file-type Build Status

Detect the file type of a Buffer/Uint8Array

The file type is detected by checking the magic number of the buffer.

Install

$ npm install --save file-type

Usage

CLI

node fileInspector --file PATH_TO_FILE [--showSignature]
OR
node httpInspector --url URL_TO_FILE [--showSignature]

If you use optional parameter "showSignature" the signature is shown even if the file type is detected.

Node.js
const readChunk = require('read-chunk'); // npm install read-chunk
const fileType = require('file-type');
const buffer = readChunk.sync('unicorn.png', 0, 262);

fileType(buffer);
//=> {ext: 'png', mime: 'image/png'}

or from a remote location:

const http = require('http');
const fileType = require('file-type');
const url = 'http:https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif';

http.get(url, res => {
	res.once('data', chunk => {
		res.destroy();
		console.log(fileType(chunk));
		//=> {ext: 'gif', mime: 'image/gif'}
	});
});
Browser
const xhr = new XMLHttpRequest();
xhr.open('GET', 'unicorn.png');
xhr.responseType = 'arraybuffer';

xhr.onload = () => {
	fileType(new Uint8Array(this.response));
	//=> {ext: 'png', mime: 'image/png'}
};

xhr.send();

API

fileType(buffer)

Returns an Object (or null when no match) with:

buffer

Type: Buffer Uint8Array

It only needs the first 262 bytes.

Supported file types

SVG isn't included as it requires the whole file to be read, but you can get it here.

PR welcome for additional commonly used file types.

Add new magic numbers

Determine the magic numbers by using the readChunk result to create a signature:

var signature = "";
for(var x = 0; x < 20; x++) {
    if (result[x]) signature += result[x].toString(16)+' ';
}

Use this signature to compare it with a list of magic numbers - see below for sources

Test local files

Use the fileInspector.js to test local files. Please edit the file and add your fileName and then call:

node fileInspector.js

Result: 
DETECTED { ext: 'vtt', mime: 'text/plain' }

Magic Number lists and databases

Related

License

MIT © Sindre Sorhus

About

Detect the file type of a Buffer/Uint8Array

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 96.9%
  • PostScript 1.4%
  • Rich Text Format 1.1%
  • Makefile 0.6%