jsrosetta

Collections

Buffer

Buffer.alloc, writeUIntBE/LE và Buffer.compare của Node.js so với []byte (Go), &mut [u8] (Rust), [UInt8] (Swift) và byte[] (Java).

Phiên bản tối thiểu
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.58Swift ≥ 3.0Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Buffer trong Node.js là API cấp cao để làm việc với dữ liệu nhị phân, có sẵn method đọc/ghi big-endian và little-endian. Go không có kiểu Buffer riêng — bạn thao tác trực tiếp trên []byte bằng các package chuẩn encoding/binary, encoding/hex và bytes. Rust, Swift và Java cũng không có sẵn method kiểu writeUIntBE/writeUIntLE cho độ dài byte tuỳ ý — cả ba đều phải tự viết bằng dịch bit (>>, &), y hệt cách làm ở Go.

Ghi số nguyên theo big-endian / little-endian

const buf = Buffer.alloc(6)
 
const value = 0x1234567890ab
buf.writeUIntBE(value, 0, 6)
console.log(buf.toString('hex')) // 1234567890ab
 
const buf2 = Buffer.alloc(6)
buf2.writeUIntLE(value, 0, 6)
console.log(buf2.toString('hex')) // ab9078563412

So sánh hai buffer

let isEqual = Buffer.compare(buf, buf2) === 0
console.log(isEqual) // false
 
isEqual = Buffer.compare(buf, buf) === 0
console.log(isEqual) // true

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#buffers