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
How to Install Node on Windows, macOS and Linux
Getting Started with Electron
Best Visual Studio Code Extensions for 2022
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
Using Puppeteer and Jest for End-to-End Testing
Build a Real-Time Chat App with Node, Express, and Socket.io
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
