Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
About the Author
About the Reviewers

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 first line of our example makes a buffer, populating it with the string Hello world.

The Buffer class includes the toString method, which takes a single argument, the means to encode the buffer. Here, we're passing base64, indicating that we want s to...