DEV Community

Vivek Kumar
Vivek Kumar

Posted on

Understanding Buffer data in Node js

I will keep this article short, the reason behind that is like, there can be so many questions you can explore yourself related to binary, buffer data, etc.

In this tutorial, what I am going to do is, I will help you understand buffer data, how it gets created.

In node js if you want to create one buffer, you can use one method called
However, there are other ways as well as, which you can explore and comment below.

So, when you create buffer, you can create something like this

const buff = Buffer.alloc(8)

Here 8 is the size of buffer, means 8 bytes.
1 byte = 8 bits

  • 00000000 in binary
  • 00 in hexadecimal

If you print buff in terminal you will see below output
<Buffer 00 00 00 00 00 00 00 00>

If you notice we have 8 pairs of zeroes - that represent 8 bytes in hexadecimal.

If you are a UI developer, you might be aware of hex color code where we use FF or AF or 3E etc, these are actually hexadecimal

Lets take an example.

We want to store "hello" in buffer.
By looking at the word we can easily see, it has 5 characters.
If we can store each character in 1 byte, we will need 5 bytes of buffer.

Lets create a new buffer

const helloBuff = Buffer.alloc(5)
<Buffer 00 00 00 00 00>
Enter fullscreen mode Exit fullscreen mode

As I told you each pair of zeroes represents one byte of hexadecimal number.

So what we can do here is, we can transform each character of "hello" to hexadecimal number.

To do that first we will have to convert it into it's ASCII value

'h' is 104 - 68 in hexadecimal
'e' is 101 - 65 in hexadecimal 
'l' is 108 - 6C in hexadecimal
'l' is 108 - 6C in hexadecimal
'o' is 111 - 6F in hexadecimal
Enter fullscreen mode Exit fullscreen mode

To convert a decimal (say 108) to hexadecimal (say 6C ) follow below steps

  • Divide 108 by 16.
  • Quotient: 6, Remainder: 12
  • Continue dividing the quotient (6) by 16
  • Quotient: 0 (Stop since the quotient is now zero). Remainder is 6
  • Write in reverse order i.e. 6C ( here we can represent 12 as C in hex)

So our buffer data should be like

<Buffer 68 65 6C 6C 6F>

Now that we know what will be the output, we can test it now.

Enter fullscreen mode Exit fullscreen mode

If you try to log helloBuff, your output will be same.

You can also use toString() method to get proper values

for e.g.

helloBuff.toString('utf8'). //output - 'hello'
helloBuff.toString('base64') //output - 'aGVsbG8='
helloBuff.toString('hex') //output - '68656c6c6f'
Enter fullscreen mode Exit fullscreen mode

If you want to learn to calculate any string to base64 string. Please check my other article.

Top comments (0)