← Back to Node.js Course | Chapter 2: Core Modules | Lesson 7 of 7

Buffer basics

A Buffer is a fixed-size chunk of raw bytes, used for binary data like files and network packets.

In this page:

  1. Buffer basics
Syntax
javascript
const buf = Buffer.from('text', 'utf8');
const empty = Buffer.alloc(size);
buf.toString('hex');

Buffer basics

Buffer.from creates a buffer from a string, array or another buffer, and Buffer.alloc creates a zero-filled one. toString converts bytes back to text using an encoding such as utf8, hex or base64. Buffers are a subclass of Uint8Array.

Note: Buffer.alloc is safer than the old Buffer constructor because it zero-fills memory.

Example: Buffer basics

javascript
const b = Buffer.from("héllo", "utf8");
console.log("chars:", "héllo".length, "bytes:", b.length);
console.log(b.toString("hex"));
console.log(Buffer.from("Node").toString("base64"));
console.log(Buffer.alloc(3));

// Output:
// chars: 5 bytes: 6
// 68c3a96c6c6f
// Tm9kZQ==
// <Buffer 00 00 00>

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using the deprecated new Buffer()
  2. Mixing up string length and byte length
  3. Forgetting the encoding when converting
Chapter Summary
  • Buffer holds raw bytes
  • from and alloc create buffers
  • toString takes an encoding
  • Buffers are Uint8Arrays
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.