How to use the Buffer toString Function in Node
Table of Contents
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.
JAVASCRIPTconst buffer = Buffer.from("Hello World");
console.log(buffer);
BASH<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.
JAVASCRIPTconst buffer = Buffer.from("Hello World");
const string = buffer.toString();
console.log(string);
BASHHello 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.
JAVASCRIPTconst buffer = Buffer.from("Hello World");
const string = buffer.toString("utf-8");
console.log(string);
BASHHello World
Other types of encodings include hex
and base64
.
For example, this is how this looks in hex
:
JAVASCRIPTconst buffer = Buffer.from("Hello World");
const string = buffer.toString("hex");
console.log(string);
BASH48656c6c6f20576f726c64
Here it is in base64
:
JAVASCRIPTconst buffer = Buffer.from("Hello World");
const string = buffer.toString("base64");
console.log(string);
BASHSGVsbG8gV29ybGQ=
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!
- Getting Started with TypeScript
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Create an RSS Reader in Node
- Getting Started with Electron
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications