codejump
EasyJavaScriptTypeScript

Node.js — Read Magic Bytes with Buffer

Node.jsBackendBuffers

A file name can lie; its first bytes rarely do. Every PNG starts with 89 50 4E 47 0D 0A 1A 0A,
every PDF with %PDF-. Node handles raw bytes with
[`Buffer`](https://nodejs.org/api/buffer.html), and tinyserve will use this to describe files.

Your task

Write describeFile(buffer) and return { type, size, preview }:

  • type — the first entry of SIGNATURES whose magic bytes (written in hex) start the

buffer. Otherwise:
- 'text/plain; charset=utf-8' if the buffer is non-empty, contains no 0x00 byte and is
valid UTF-8;
- 'application/octet-stream' in every other case (empty buffer included).

  • size — the length in bytes. 'héllo' is 5 characters but 6 bytes: é takes two.
  • preview — the first 8 bytes (fewer if the buffer is shorter) as lowercase two-digit hex,

separated by spaces: '89 50 4e 47 0d 0a 1a 0a'.

The test driver builds the buffer from a base64 string, so the tests can carry binary data.

Valid UTF-8?

buffer.toString('utf8') never throws: invalid sequences become � (U+FFFD). Encoding that
string back gives different bytes, so Buffer.from(text, 'utf8').equals(buffer) is a valid test.

Example

describeFile(Buffer.from('héllo'));
// → { type: 'text/plain; charset=utf-8', size: 6, preview: '68 c3 a9 6c 6c 6f' }

Sample tests

Test #1PNG header
Input: ["iVBORw0KGgoAAAANSUhEUg=="]
Output: {"size":16,"type":"image/png","preview":"89 50 4e 47 0d 0a 1a 0a"}
Test #2UTF-8 text: 5 characters, 6 bytes
Input: ["aMOpbGxv"]
Output: {"size":6,"type":"text/plain; charset=utf-8","preview":"68 c3 a9 6c 6c 6f"}
Test #3PDF
Input: ["JVBERi0xLjcK"]
Output: {"size":9,"type":"application/pdf","preview":"25 50 44 46 2d 31 2e 37"}
Test #4Binary bytes
Input: ["//4AAQ=="]
Output: {"size":4,"type":"application/octet-stream","preview":"ff fe 00 01"}