1
0

Identification of image and mp4 file types in node


 invite response                
2022 Nov 9, 4:11pm   42 views  0 comments

by Patrick   ➕follow (55)   💰tip   ignore  

Just because it took me a while to figure out how to identify file types in node, I thought I'd share it with the world:


async function file_type(filepath) {
const CHUNK_SIZE = 12; // bytes to read at a time; no need to read the rest of the file after the first 12 bytes

const stream = fs.createReadStream(filepath, { highWaterMark: CHUNK_SIZE });
for await(const data of stream) { // early return will prevent wasteful reading of entire file
const bytes = [];
data.forEach(byte => bytes.push(byte.toString(16)));
const hex = bytes.join('');

if (hex.includes('47494638')) return 'gif';
if (hex.includes('66747970')) return 'mp4'; // magic number for mp4 starts at offset 4
if (hex.includes('89504e47')) return 'png';
if (hex.includes('ffd8ff')) return 'jpg';
if (hex.includes('57454250')) return 'webp'; // magic number for webp starts at offset 8, goes to 11
//if (hex.includes('25504446')) return 'pdf';
//if (hex.includes('504b0304')) return 'zip';
return false;
}
}
no comments found

Please register to comment:

api   best comments   contact   latest images   memes   one year ago   random   suggestions