0
0
Node.jsframework~5 mins

Reading and writing buffer data in Node.js

Choose your learning style9 modes available
Introduction

Buffers let you handle raw binary data in Node.js. They help you read and write data like files or network streams easily.

Reading data from a file or network where data is in binary form.
Writing binary data to a file or sending it over a network.
Manipulating raw data like images or audio before processing.
Converting strings to bytes and back for encoding or decoding.
Syntax
Node.js
const buffer = Buffer.from(stringOrArray);
const byte = buffer[index];
buffer[index] = newByte;
const str = buffer.toString(encoding);

Buffers are like arrays but hold raw bytes (numbers from 0 to 255).

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

Examples
Creates a buffer from the string 'hello'.
Node.js
const buf = Buffer.from('hello');
console.log(buf);
Creates an empty buffer of length 5, sets first byte to 'H', then prints the string.
Node.js
const buf = Buffer.alloc(5);
buf[0] = 72; // ASCII for 'H'
console.log(buf.toString());
Creates a buffer from an array of bytes representing 'Hello'.
Node.js
const buf = Buffer.from([72, 101, 108, 108, 111]);
console.log(buf.toString());
Sample Program

This program shows how to create a buffer from a string, read a byte, modify it, and convert back to a string.

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

// Create a buffer from a string
const buf = Buffer.from('Node.js');

// Read bytes from buffer
const firstByte = buf[0];

// Change a byte (e.g., change 'N' to 'n')
buf[0] = 110;

// Convert buffer back to string
const newString = buf.toString();

console.log('Original first byte:', firstByte);
console.log('Modified buffer as string:', newString);
OutputSuccess
Important Notes

Buffer indexes start at 0, like arrays.

Changing a byte changes the data directly in the buffer.

Use buffer.toString() to read buffer content as text.

Summary

Buffers hold raw binary data in Node.js.

You can read and write bytes directly using indexes.

Buffers convert easily between strings and binary data.