实现说明
bytes、view、signature、isPng 定义在模块顶层,中间不经过函数作用域。
使用要点
- 演示输出是带标签的(
signature: 0x、png:、patched bytes 6-7:),每个操作都会留下自己的一行标注。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 状态都挂在模块顶层:bytes、view、signature。
核心语句
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;
代码示例
// 文件头魔数检查: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));