Node Buffers

Question Click to View Answer

Is JavaScript well equipped to deal with binary data?

JavaScript was built to manipulate text documents (the DOM), so it's not well suited to deal with binary data. Server side JavaScript needs to process binary data to interact with databases and other APIs.

Node includes a binary buffer implementation to make it easier to work with bytes in JavaScript.

Create a buffer of the UTF-8 encoded string "train".

const trainBuf = new Buffer("train");

Buffers can be created by instantiating the Buffer pseudoclass.

Access the third byte of the following buffer.

const planeBuf = new Buffer("plane");
const planeBuf = new Buffer("plane");
console.log(planeBuf[2]);

A buffer is an ordered list and the elements can be accessed with indexing, similar to a list.

Convert carBuf back to a string.

const carBuf = new Buffer("car");
carBuf.toString();

The toString() method converts a buffer to a string. This is referred to as "decoding" a UTF-8 encoded string.

What does the following code print to the console?

let someBuf = new Buffer("dog");
someBuf[0] = 104;
console.log(someBuf.toString());

"hog" is printed.

The Buffer pseudoclass encodes the "dog" string with UTF-8 encoding. The first element of the someBuf buffer is changed to character 104, which maps to the letter "h". someBuf was mutated to the "hog" string.

How many different characters can be encoded with UTF-8?

Each UTF-8 character consists of 1 byte (8 bits). Each bit can hold two values, so 8 bits can represent 256 different values (Math.pow(2, 8)).

What does the following code print?

let boringBuf = new Buffer('8b76fde713ce', 'base64');
let result = boringBuf.toString('base64')
console.log(result)

"8b76fde713ce" is printed.

The boringBuf variable encodes "8b76fde713ce" as a base64 string.

The result variable decodes the boringBuf buffer.

How many different characters can be encoded with base64 encoding?

base64 encoding supports 64 bits (8 bytes). Each bit can hold two values, so 64 bits can represent 18446744073709552000 different values (Math.pow(2, 64)).

Why is UTF-8 the dominant encoding of the web?

UTF-8 is efficient because it only requires 1 byte of storage per character. UTF-8 can support all the numbers, lowercase letters, uppercase letters, and special symbols of Western languages so it is often enough to get the job done. Different encoding schemes are needed for languages with more than 256 characters.