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 ...
Get JavaScript JSON Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.