buf.write(string[, offset[, length]][, encoding]),向buffer写入字符串
buf.writeDoubleBE(value, offset[, noAssert])写入64位浮点型数字,大端对齐
buf.writeDoubleLE(value, offset[, noAssert]),写入64位浮点型数字,小端对齐
buf.writeFloatBE(value, offset[, noAssert]),写入32位浮点型数字,大端对齐
buf.writeFloatLE(value, offset[, noAssert]),写入32位浮点型数字,小端对齐
buf.writeInt8(value, offset[, noAssert]),写入有符号8位整型数字
buf.writeInt16BE(value, offset[, noAssert]),写入有符号16位整型数字,大端对齐
buf.writeInt16LE(value, offset[, noAssert]),写入有符号16位整型数字,小端对齐
buf.writeInt32BE(value, offset[, noAssert]),写入有符号32位整型数字,大端对齐
buf.writeInt32LE(value, offset[, noAssert]),写入有符号32位整型数字,小端对齐
buf.writeIntBE(value, offset, byteLength[, noAssert]),以下便不再累述
buf.writeIntLE(value, offset, byteLength[, noAssert])
buf.writeUInt8(value, offset[, noAssert])
buf.writeUInt16BE(value, offset[, noAssert])
buf.writeUInt16LE(value, offset[, noAssert])
buf.writeUInt32BE(value, offset[, noAssert])
buf.writeUInt32LE(value, offset[, noAssert])
buf.writeUIntBE(value, offset, byteLength[, noAssert])
buf.writeUIntLE(value, offset, byteLength[, noAssert])
buffer读操作由read开头的api完成,主要有以下这些:
buf.readDoubleBE(offset[, noAssert])
buf.readDoubleLE(offset[, noAssert])
buf.readFloatBE(offset[, noAssert])
buf.readFloatLE(offset[, noAssert])
buf.readInt8(offset[, noAssert])
buf.readInt16BE(offset[, noAssert])
buf.readInt16LE(offset[, noAssert])
buf.readInt32BE(offset[, noAssert])
buf.readInt32LE(offset[, noAssert])
buf.readIntBE(offset, byteLength[, noAssert])
buf.readIntLE(offset, byteLength[, noAssert])
buf.readUInt8(offset[, noAssert])
buf.readUInt16BE(offset[, noAssert])
buf.readUInt16LE(offset[, noAssert])
buf.readUInt32BE(offset[, noAssert])
buf.readUInt32LE(offset[, noAssert])
buf.readUIntBE(offset, byteLength[, noAssert])
buf.readUIntLE(offset, byteLength[, noAssert])
使用如下所示,以32无符号整型为例:
const buf = Buffer.allocUnsafe(8);
buf.writeUInt32BE(0x12345678,0)
console.log(buf);
const data = buf.readUInt32BE(0);
console.log(data.toString(16));最后利用buffer读API完成一个获取PNG格式图片尺寸的小工具,在开始编码之前,先简单介绍下PNG文件组成,如下所示:
| PNG文件标志 | PNG数据块 | …… | PNG数据块 |
|---|
这里我们只要用到PNG文件标识和PNG数据块的第一个块IHDR文件头数据块。文件标识是固定的8个字节,为









