ข้ามไปยังเนื้อหา

Buffer

JavaScript strings ถูกเก็บภายในเป็น UTF-16 — สอง bytes ต่อ code point ใน Basic Multilingual Plane ซึ่งใช้ได้ดีสำหรับข้อความ แต่งาน networking และ filesystem จัดการ raw bytes: TCP packet, ภาพ JPEG หรือ binary protocol frame ไม่มี encoding ในตัว

Buffer คือคำตอบของ Node: ลำดับของ bytes ที่มีขนาดคงที่ ที่ expose เป็น Uint8Array subclass มีมาก่อน typed arrays และยังคงเป็น type มาตรฐานที่คุณจะเห็นใน Node’s streams, HTTP, crypto และ fs APIs

วิธีที่แนะนำคือ Buffer.from() constructor new Buffer() ที่ deprecated ถูกลบออกไปแล้ว อย่าใช้

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

toString(encoding) แปลง Buffer กลับเป็น string ใน encoding ที่ต้องการ

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

buf.slice(start, end) (หรือ buf.subarray) คืน view ไปยัง memory เดียวกัน — การแก้ไข slice จะแก้ไข original ด้วย ใช้ Buffer.from(slice) เพื่อได้ copy อิสระ

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

ทำไม Buffer.byteLength(str) ถึงมักต่างจาก str.length?
Buffer.from("deadbeef", "hex") ให้ผลลัพธ์อะไร?
เกิดอะไรขึ้นเมื่อคุณแก้ไข slice ที่ได้จาก buf.slice()?