joshtronic

Posted in Software Development #Node.js

Convert a buffer to a string in Node.js

Buffers are powerful stuff. They make it easy to work with raw binary data, and streaming data can leverage them. Many third-party Node.js dependencies leverage buffers in one way or another, especially libraries dealing with data transport.

So what the heck are we supposed to do with a Buffer when we have one?

Obviously that depends on what you're trying to do. You could very well pass the Buffer object along to a library for processing.

Or, as the title of this post suggests, convert the Buffer object into a good ol' string, which you can do so with as you please.

Assuming you don't have a buffer readily available, you can create one quite easily like this:

const buffer = Buffer.from('I am a buffer!', 'utf-8');

While we already know what the buffer contains, since we defined the string, let's take a look at what the buffer looks like, so we can get a sense for how things would look when we don't know what the buffer contains:

console.log(buffer);
// <Buffer 49 20 61 6d 20 61 20 62 75 66 66 65 72 21>

The buffer is effectively just an array of integers that represent the data that it contains.

To get a string back out of the buffer, simply use .toString():

console.log(buffer.toString());
// 'I am a buffer!'