Using the Buffer `toString()` Function in Node.js

Aug 21, 2020

Node.js buffers are objects that store arbitrary binary data. Buffers have a toString() method that you can use to convert the buffer to a string.

By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer.from(), the toString() function gives you the original string back.

const buf = Buffer.from('Hello, World', 'utf8');

buf.toString(); // 'Hello, World'

The encoding Parameter

The toString() method's first parameter is a string called encoding. It determines what format Node.js uses to express the raw data. The default value is 'utf8'.

const fs = require('fs');

const buf = fs.readFileSync('./package.json');
buf.toString('utf8'); // '{ "name": "masteringjs.io", ...}'

Node.js supports numerous different encodings for buffers. The most commonly used are:

For example, by calling .toString('hex'), you get a string representation of the buffer where each byte is encoded as 2 hexadecimal characters.

const fs = require('fs');

const buf = fs.readFileSync('./package.json');
buf.toString('hex'); // '7b0a2020...'

Which encoding is correct depends on your use case and the data stored in the buffer. Typically Buffer#toString() is used for debugging and trying to figure out what the contents of the buffer mean. If that's your use case, try all 3 different encodings and see if any of them look familiar.

One common use case for .toString() is converting a file to base64 so it can be used as an email attachment. Here's how you can convert a file to base64 encoding using Node.js:

const fs = require('fs');

const buf = fs.readFileSync('./package.json');
buf.toString('base64'); // 'ewogICJuYW1lI...'

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Node Tutorials