How to use the Buffer toString Function in Node

Updated onbyAlan Morel
How to use the Buffer toString Function in Node

Buffers in Node are used to store arbitrary data, usually in the binary format.

In some situations, you'll need to be able to convert a buffer to a string, maybe to then be displayed to the user, or to be written to a file.

In this post, we'll learn how to convert a buffer to a string in Node.

How to convert a buffer to a string in Node

The easiest way to convert a buffer to a string is to use the toString() method.

Let's start off with an example buffer by building a buffer using the Buffer.from() method.

const buffer = Buffer.from("Hello World");

console.log(buffer);
<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>

As you can see, the buffer right now is not human readable just yet.

However, now that we have our buffer, we can then use the toString() method to convert it to a string.

const buffer = Buffer.from("Hello World");

const string = buffer.toString();

console.log(string);
Hello World

By default, the toString() method will convert the buffer to a string using the default encoding, however, you can specify the type of encoding that you want by passing it as an argument.

const buffer = Buffer.from("Hello World");

const string = buffer.toString("utf-8");

console.log(string);
Hello World

Other types of encodings include hex and base64.

For example, this is how this looks in hex:

const buffer = Buffer.from("Hello World");

const string = buffer.toString("hex");

console.log(string);
48656c6c6f20576f726c64

Here it is in base64:

const buffer = Buffer.from("Hello World");

const string = buffer.toString("base64");

console.log(string);
SGVsbG8gV29ybGQ=

Conclusion

In this post, we learned how to convert a buffer to a string in Node.

You can just call toString() on a buffer and it will convert it to a string with the encoding that you specify.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.