Core Modules

Node.js Buffer

Working with Buffers

Node.js Buffer handles binary data for streams and files.

Introduction to Node.js Buffer

The Node.js Buffer class is a global object used for handling binary data directly. It is particularly useful when dealing with streams or reading from files, where you need to manipulate raw bytes. Buffers are instances of the Buffer class in Node.js and are designed to work with TCP streams, file system operations, and other data that requires direct binary handling.

Creating Buffers

You can create a Buffer in Node.js using several methods:

  • Buffer.from() - Creates a new buffer from an existing array, string, or buffer.
  • Buffer.alloc() - Allocates a new buffer of a specified size, initialized with zeros.
  • Buffer.allocUnsafe() - Allocates a new buffer of a specified size, but does not initialize it, which can be faster but might contain old data.

Writing to Buffers

Once a buffer is created, you can write data into it using several methods such as buf.write(). This function allows you to specify the data to write, the encoding, and the starting index.

Reading from Buffers

Reading data from a buffer can be done using methods like buf.toString(), which converts the buffer to a string using a specified encoding, such as UTF-8.

Buffer Concatenation

Buffers can be concatenated using Buffer.concat(). This is particularly useful when dealing with streams, where data might be received in chunks.

Conclusion

The Node.js Buffer class is a powerful tool for handling binary data, making it an essential part of Node.js for working with streams and files. Understanding how to create, manipulate, and read buffers allows developers to efficiently handle various data formats and sources.