0
0
Node.jsframework~5 mins

Why buffers are needed in Node.js

Choose your learning style9 modes available
Introduction

Buffers let Node.js handle raw binary data. They help work with files, network data, or images that are not just text.

Reading or writing files like images or videos.
Receiving data from a network connection.
Working with streams of binary data.
Manipulating data that is not plain text, like encrypted data.
Syntax
Node.js
const buffer = Buffer.from('hello');
Buffers store raw bytes, not characters.
You can create buffers from strings, arrays, or allocate fixed sizes.
Examples
Creates a buffer from a string.
Node.js
const buf1 = Buffer.from('hello');
Creates a buffer of 5 bytes filled with zeros.
Node.js
const buf2 = Buffer.alloc(5);
Creates a buffer from an array of bytes.
Node.js
const buf3 = Buffer.from([1, 2, 3]);
Sample Program

This code creates a buffer from the string 'Hi!'. It prints the raw bytes and then converts it back to a string.

Node.js
import { Buffer } from 'node:buffer';

const buf = Buffer.from('Hi!');
console.log(buf);
console.log(buf.toString());
OutputSuccess
Important Notes

Buffers are fixed size and hold raw binary data.

They are essential for working with non-text data in Node.js.

Summary

Buffers store raw binary data in Node.js.

They are needed when working with files, networks, or any non-text data.

You can create buffers from strings, arrays, or allocate empty space.