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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Getting Started with Sass
Learn how to use v-model with a custom Vue component
Getting Started with Handlebars.js
Build a Real-Time Chat App with Node, Express, and Socket.io
Creating a Twitter bot with Node.js
Setting Up Stylus CSS Preprocessor
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
How To Create a Modal Popup Box with CSS and JavaScript
Getting Started with Moon.js
