Buffer
ทำไม Buffer ถึงมีอยู่
หัวข้อที่มีชื่อว่า “ทำไม 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
หัวข้อที่มีชื่อว่า “การสร้าง Buffer”วิธีที่แนะนำคือ Buffer.from() constructor new Buffer() ที่ deprecated ถูกลบออกไปแล้ว อย่าใช้
Needs the Node.js runtime — open in StackBlitz to run.
Encodings: utf8, hex, base64
หัวข้อที่มีชื่อว่า “Encodings: utf8, hex, base64”toString(encoding) แปลง Buffer กลับเป็น string ใน encoding ที่ต้องการ
Needs the Node.js runtime — open in StackBlitz to run.
Byte length vs string length
หัวข้อที่มีชื่อว่า “Byte length vs string length”Needs the Node.js runtime — open in StackBlitz to run.
Slicing และ copying
หัวข้อที่มีชื่อว่า “Slicing และ copying”buf.slice(start, end) (หรือ buf.subarray) คืน view ไปยัง memory เดียวกัน — การแก้ไข slice จะแก้ไข original ด้วย ใช้ Buffer.from(slice) เพื่อได้ copy อิสระ
Needs the Node.js runtime — open in StackBlitz to run.