A buffer is a specific location in raw memory.

Node.js includes a Buffer class.

Learn how to create, read, and change the contents of a buffer.

a person holding up a node.js sticker

Its useful when you dont have any data to store at the time of buffer creation.

Specify the buffer size parameter in bytes when you create a buffer with thealloc()method.

The Buffer class expresses each 0 value as00, using hexadecimal format.

In this example, it contains a total of eight values.

Note that although you passed a number as thefillparameter, buffers only store data in binary.

Adding a second character to the string will fill up the second byte.

To extract data from existing data types like strings or arrays, use thefrom()method.

This method creates buffers from strings and arrays.

Passing numbers to thefrom()method will result in an error.

The Buffer class allows us to read individual bytes of its data using JavaScript’s square bracket syntax.

Attempting to get an invalid byte will result in anundefinederror.

In the final case, a Buffer with fivenull valuesreturns the string \x00\x00\x00\x00\x00.

The string\x00is the hexadecimal representation of null.

The JSON output has atypeproperty with a value ofBufferto indicate its origin.

Its data property stores an array of decimals that represent the original byte array.

Because buffers are binary data, you cannot give a specific portion of a buffer a string.

Consider inserting an index outside the Buffer’s length.

Rather than returning an error, Buffer ignores the invalid index and keeps the original Buffer content intact.

Buffers write in a serial fashion beginning at index zero.

Thewrite()method serially adds bytes to a Buffer, overwriting any previous data.

The code above creates a six-byte buffer and adds the string memberto it using thewrite()method.

It then updates the buffer with new content that takes up less memory space than the earlier content.

There are several other methods available to work with the Node.js Buffer class.

You should know these methods and understand Buffers to grasp how different concepts like streams and file systems work.