有時候我們會需要以指定的資料形態讀寫 Buffer,例如:
const buf = Buffer.allocUnsafe(4)
buf.writeUInt32BE(0x01020304, 0)
console.log(buf.toString('hex')) // 01020304
buf.writeUInt32LE(0x01020304, 0)
console.log(buf.toString('hex')) // 04030201
Buffer 支援的資料形態及相對應的讀寫函式如下:
Data type | Big Endian Read/Write function | Little Endian Read/Write function |
---|---|---|
BigInt64 | readBigInt64BE / writeBigInt64BE | readBigInt64LE / writeBigInt64LE |
BigUInt64 | readBigUInt64BE / writeBigUInt64BE | readBigUInt64LE / writeBigUInt64LE |
Double | readDoubleBE / writeDoubleBE | readDoubleLE / writeDoubleLE |
Float | readFloatBE / writeFloatBE | readFloatLE / writeFloatLE |
Int | readIntBE / writeIntBE | readIntLE / writeIntLE |
Int16 | readInt16BE / writeInt16BE | readInt16LE / writeInt16LE |
Int32 | readInt32BE / writeInt32BE | readInt32LE / writeInt32LE |
UInt | readUIntBE / writeUIntBE | readUIntLE / writeUIntLE |
UInt16 | readUInt16BE / writeUInt16BE | readUInt16LE / writeUInt16LE |
UInt32 | readUInt32BE / writeUInt32BE | readUInt32LE / writeUInt32LE |
如果想要把 Buffer 中的資料複製到另一個,可以使用來自 Uint8Array 的 set()
函式:
const buf1 = Buffer.allocUnsafe(8)
const buf2 = Buffer.from('ABC')
buf1.set(buf2, 3)
console.log(buf1.toString('hex')) // 0000004142430000
也可以使用 copy()
函式:
const buf1 = Buffer.allocUnsafe(26)
const buf2 = Buffer.allocUnsafe(26).fill('!')
for (let i = 0; i < 26; i++) buf1[i] = i + 97
buf1.copy(buf2, 8, 16, 20)
console.log(buf2.toString('ascii'))
// !!!!!!!!qrst!!!!!!!!!!!!!