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.
0
0
Creating buffers in Node.js
Introduction
Reading or writing files in binary format.
Handling data from network connections like TCP sockets.
Working with streams that send or receive raw bytes.
Manipulating images or audio data in memory.
Converting strings to binary data for encoding or decoding.
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
Creates a buffer of 5 bytes, all set to zero.
Node.js
const buf = Buffer.alloc(5);
console.log(buf);Creates a buffer from an array of numbers representing bytes.
Node.js
const buf = Buffer.from([10, 20, 30]); console.log(buf);
Creates a buffer from a string using UTF-8 encoding.
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);
OutputSuccess
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.