In Node.js, the
Buffers can be created in several ways:
- Using the
const buf = Buffer.alloc(10); // Create a buffer of size 10 bytes, filled with zeros
- Using the
const buf1 = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); // Create a buffer from an array of bytes const buf2 = Buffer.from('buffer', 'utf-8'); // Create a buffer from a string const buf3 = Buffer.from(buf2); // Create a buffer by copying the content of another buffer
Once a buffer is created, you can access its individual bytes using array-like indexing:
const buf = Buffer.from('hello'); console.log(buf); // 104 (ASCII value of 'h') console.log(buf); // 101 (ASCII value of 'e') console.log(buf); // 108 (ASCII value of 'l') // ...
Buffers provide methods for various operations, including slicing, copying, converting to different encodings, and more. Some commonly used methods include:
buffer.slice(start[, end]): Creates a new buffer that references a portion of the original buffer.
buffer.toString([encoding[, start[, end]]]): Converts the buffer contents to a string using the specified encoding.
buffer.copy(target[, targetStart[, sourceStart[, sourceEnd]]]): Copies data from one buffer to another.
buffer.length: Returns the length (in bytes) of the buffer.
Here’s an example that demonstrates some basic operations with buffers:
const buf1 = Buffer.from('Hello'); const buf2 = Buffer.from('World'); const buf3 = Buffer.concat([buf1, buf2]); // Concatenate two buffers console.log(buf3.toString()); // 'HelloWorld' console.log(buf3.length); // 10 const slice = buf3.slice(5, 8); // Get a slice of the buffer console.log(slice.toString()); // 'Wor'
Buffers are widely used in Node.js for handling binary data efficiently, such as reading and writing files, network communication, cryptography, and other low-level operations. However, it’s important to be cautious when working with buffers to avoid potential security vulnerabilities, such as buffer overflows or information leaks