O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Encoding binary data as a base64 string using Node.js

If you have binary data that you need to encode to pass to the client as JSON, you can convert it to base64, a common means on the Internet to represent eight-bit values in solely printable characters. Node.js provides the Buffer object and a base64 encoder and decoder for this task.

How to do it…

First, you'll allocate a buffer, and then you'll convert it to a string, indicating that the string you want should be base64-encoded, like this:

var buffer = newBuffer('Hello world');
var string = buffer.toString('base64');

How it works…

The Node.js Buffer class wraps a collection of octets outside the Node.js V8 runtime heap. It's used in Node.js anytime you need to work with purely binary data. The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required