DataView Reads Binary File Headers

Read upload magic numbers with DataView: getUint32 compares the PNG signature, getUint16 distinguishes JPEG, and setUint16 patches bytes in place.

JavascriptFile Upload

Code

javascriptsnippet
15 lines
// 文件头魔数检查:DataView 按字节偏移读取上传内容的前几字节
// PNG 以 89 50 4E 47 开头,JPEG 以 FF D8 开头
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const view = new DataView(bytes.buffer);

const signature = view.getUint32(0); // 大端读取前 4 字节
console.log('signature: 0x' + signature.toString(16));

const isPng = signature === 0x89504e47;
const isJpeg = view.getUint16(0) === 0xffd8;
console.log('png:', isPng, 'jpeg:', isJpeg);

// 写入同样按偏移进行:改写第 6-7 字节再读回
view.setUint16(6, 0x0000);
console.log('patched bytes 6-7:', view.getUint8(6), view.getUint8(7));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

signature: 0x89504e47
png: true jpeg: false
patched bytes 6-7: 0 0

What the code does

Module-level bindings hold the data — bytes, view, signature, isPng — with no function scope in between.

Applying it

The demo output is labeled (signature: 0x, png:, patched bytes 6-7:), so every printed line maps back to its originating operation.

Statements that matter

const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const signature = view.getUint32(0); // 大端读取前 4 字节
console.log('signature: 0x' + signature.toString(16));
const isJpeg = view.getUint16(0) === 0xffd8;

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `bytes`, `view`, `signature`.