Node.js — Read Magic Bytes with Buffer
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 ofSIGNATURESwhosemagicbytes (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