Encoding and Decoding
The Buffer
class supports various character encodings, including UTF-8, ASCII, Base64, and hexadecimal. Developers can specify the encoding format when converting between buffers and strings using the toString()
and from()
methods.
const buffer = Buffer.from('Hello, World!', 'utf8');
// Encoding buffer to Base64
const base64String = buffer.toString('base64');
console.log(base64String); // Output: SGVsbG8sIFdvcmxkIQ==
// Decoding Base64 string to buffer
const decodedBuffer = Buffer.from(base64String, 'base64');
console.log(decodedBuffer.toString('utf8')); // Output: Hello, World!
What is the purpose of the Buffer class in Node ?
In Node, the Buffer
class plays a crucial role in handling binary data, allowing developers to work with raw binary data directly. The Buffer
class provides a way to create, manipulate, and convert binary data efficiently, making it essential for various tasks such as file I/O, network communication, cryptography, and data manipulation. Let’s explore the key purposes and functionalities of the Buffer
class in Node.
Contact Us