ATTENTION: DO NOT USE THIS PACKAGE! Please use https://github.com/sindresorhus/file-type#readme
Detect the file type of a Buffer/Uint8Array
The file type is detected by checking the magic number of the buffer.
$ npm install --save file-type
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.
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://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'}
});
});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();Returns an Object (or null when no match) with:
ext- one of the supported file typesmime- the MIME type
Type: Buffer Uint8Array
It only needs the first 262 bytes.
jpgpnggifwebpcr2tifbmpjxrpsdziptarrargzbz27zdmgmp4m4vmidmkvwebmmovaviwmvmpgmp3m4aoggopusflacwavamrpdfepubexeswfrtfwoffwoff2eotttfotficoflvpsxzsqlitenescrxxpicabdebarrpmZlzmsi
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.
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
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' }
- http://www.garykessler.net/library/file_sigs.html
- http://tool.lu/magicbytes/
- https://gist.github.com/navinpai/983632
- http://lclevy.free.fr/raw/
- file-type-cli - CLI for this module
MIT © Sindre Sorhus