Buffers let you work with raw binary data in Node.js. They help when you need to handle files, network data, or other binary streams.
Creating buffers in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const buf = Buffer.alloc(size); const bufFromArray = Buffer.from([1, 2, 3]); const bufFromString = Buffer.from('hello', 'utf8');
Buffer.alloc(size) creates a buffer of fixed size filled with zeros.
Buffer.from() creates a buffer from an array, string, or another buffer.
Examples
Node.js
const buf = Buffer.alloc(5);
console.log(buf);Node.js
const buf = Buffer.from([10, 20, 30]); console.log(buf);
Node.js
const buf = Buffer.from('hello', 'utf8'); console.log(buf);
Sample Program
This program shows three ways to create buffers: empty with fixed size, from an array of bytes, and from a string.
Node.js
const buf1 = Buffer.alloc(4); console.log('Buffer.alloc(4):', buf1); const buf2 = Buffer.from([1, 2, 3, 4]); console.log('Buffer.from([1,2,3,4]):', buf2); const buf3 = Buffer.from('Node', 'utf8'); console.log('Buffer.from("Node", "utf8"):', buf3);
Important Notes
Buffers are fixed size and cannot be resized after creation.
Always specify encoding when creating buffers from strings to avoid confusion.
Use Buffer.alloc() to avoid uninitialized memory for security.
Summary
Buffers store raw binary data in Node.js.
Use Buffer.alloc(size) for empty buffers and Buffer.from() to create from data.
Buffers are useful for file, network, and binary data handling.
Practice
1. What does
Buffer.alloc(10) do in Node.js?easy
Solution
Step 1: Understand Buffer.alloc usage
Buffer.alloc(size)creates a buffer of the given size filled with zeros.Step 2: Analyze the argument 10
The argument 10 means the buffer will have 10 bytes, all initialized to zero.Final Answer:
Creates a buffer of 10 bytes filled with zeros -> Option AQuick Check:
Buffer.alloc(10) = zero-filled buffer [OK]
Hint: Buffer.alloc creates zero-filled buffer of given size [OK]
Common Mistakes:
- Thinking Buffer.alloc fills with random data
- Confusing Buffer.alloc with Buffer.from
- Assuming it creates an empty array
2. Which of the following is the correct syntax to create a buffer from the string 'hello'?
easy
Solution
Step 1: Recall correct Buffer creation methods
In modern Node.js,Buffer.from(string)creates a buffer from a string.Step 2: Check options
Buffer.allocexpects a size number,new Bufferis deprecated, andBuffer.createdoes not exist.Final Answer:
Buffer.from('hello') -> Option BQuick Check:
Buffer.from(string) creates buffer from string [OK]
Hint: Use Buffer.from(string) to create buffer from text [OK]
Common Mistakes:
- Using Buffer.alloc with string argument
- Using deprecated new Buffer() constructor
- Assuming Buffer.create exists
3. What will be the output of the following code?
const buf = Buffer.from('abc');
console.log(buf.length);medium
Solution
Step 1: Create buffer from string 'abc'
Buffer.from('abc')creates a buffer with bytes representing 'a', 'b', 'c'.Step 2: Check buffer length
The length property returns the number of bytes, which is 3 for 'abc'.Final Answer:
3 -> Option DQuick Check:
Buffer length of 'abc' = 3 [OK]
Hint: Buffer length equals number of bytes in string [OK]
Common Mistakes:
- Assuming length is number of characters times 2
- Expecting undefined or error
- Confusing length with string length property
4. Identify the error in this code snippet:
const buf = Buffer.alloc('5');
console.log(buf.length);medium
Solution
Step 1: Check Buffer.alloc argument type
Buffer.allocexpects a number for size, but '5' is a string.Step 2: Understand type coercion in Buffer.alloc
Passing a string causes a TypeError because size must be a number.Final Answer:
Buffer.alloc expects a number, not a string -> Option CQuick Check:
Buffer.alloc('5') causes type error [OK]
Hint: Pass number, not string, to Buffer.alloc size [OK]
Common Mistakes:
- Using string instead of number for size
- Thinking Buffer.alloc needs 'new' keyword
- Assuming length property is missing
5. You want to create a buffer from an array of bytes [72, 101, 108, 108, 111] representing 'Hello'. Which code correctly creates this buffer and converts it back to a string?
hard
Solution
Step 1: Create buffer from array of bytes
Buffer.from(array)creates a buffer from an array of byte values correctly.Step 2: Convert buffer back to string
buf.toString()converts the buffer bytes to the string 'Hello'.Step 3: Analyze other options
UsingBuffer.alloc([72,101,108,108,111])is wrong because alloc expects a number. UsingBuffer.from('72,101,108,108,111')creates a buffer from the string of numbers, not bytes. Usingbuf.write([72,101,108,108,111])is invalid as write doesn't accept arrays directly.Final Answer:
const buf = Buffer.from([72,101,108,108,111]); console.log(buf.toString()); -> Option AQuick Check:
Buffer.from(array) + toString() = 'Hello' [OK]
Hint: Use Buffer.from(array) to create buffer from bytes [OK]
Common Mistakes:
- Using Buffer.alloc with array argument
- Passing string of numbers instead of array
- Trying to write array directly into buffer
