Introduction
Buffers let you handle raw binary data in Node.js. They help you read and write data like files or network streams easily.
Jump into concepts and practice - no test required
Buffers let you handle raw binary data in Node.js. They help you read and write data like files or network streams easily.
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.
const buf = Buffer.from('hello'); console.log(buf);
const buf = Buffer.alloc(5); buf[0] = 72; // ASCII for 'H' console.log(buf.toString());
const buf = Buffer.from([72, 101, 108, 108, 111]); console.log(buf.toString());
This program shows how to create a buffer from a string, read a byte, modify it, and convert back to a string.
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);
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.
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.
Buffer in Node.js?Buffer.alloc(size) creates a zero-filled buffer.Buffer.new and Buffer.create do not exist; new Buffer() is deprecated and unsafe.const buf = Buffer.from('abc');
console.log(buf[1]);Buffer.from('abc') creates a buffer with ASCII codes of 'a', 'b', 'c'. Index 1 is 'b'.const buf = Buffer.alloc(3);
buf.write('hello');
console.log(buf.toString());src to another buffer dest starting at index 2 in dest. Which code correctly does this?source.copy(target, targetStart, sourceStart, sourceEnd).src starting at 0 to 4 bytes, into dest starting at index 2.