How to Convert Binary File Data to a Text String (Base64 Encode) in Node.js
If we want binary data to travel across text-based mediums, we’ll need to Base64 encode that data first.
Thankfully, using the below code, we can easily convert binary data to Base64 encoded text string through a free API request. We’ll just need a free API key to authorize our request, and we’ll be able to make up to 800 conversions per month with no commitments.
We can structure our API call in a few quick steps. First, let’s install the SDK by either running the following command:
npm install cloudmersive-convert-api-client --save
Or, alternatively, by adding the below snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
Finally, let’s use the below code to complete our call & supply our API key where indicated:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.EditTextApi();
var request = new CloudmersiveConvertApiClient.Base64EncodeRequest(); // Base64EncodeRequest | Input request
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.editTextBase64Encode(request, callback);
Now we can easily base64 encode our data in one quick step using minimal code.