Introduction
In this lab, we will explore how to encode a given string to base64 format using JavaScript. We will create a function that takes in a string, converts it to binary using a buffer, and then returns the base-64 encoded string. This lab aims to help learners understand the process of encoding data in base64 format and how it can be applied in real-world scenarios.
Encoding a String to Base64
To encode a String object to a base-64 encoded ASCII string, follow these steps:
- Open the Terminal/SSH and type
nodeto start coding. - Create a
Bufferusing the given string and the binary encoding. - Use
Buffer.prototype.toString()to return the base-64 encoded string.
Here's an example code snippet:
const encodeToBase64 = (str) => Buffer.from(str, "binary").toString("base64");
You can now use the encodeToBase64() function to encode any string to base-64. For example:
encodeToBase64("foobar"); // 'Zm9vYmFy'
Summary
Congratulations! You have completed the Encode String to Base64 lab. You can practice more labs in LabEx to improve your skills.