nodejs string to base64
To convert a string to Base64 in Node.js, you can follow these steps:
First, you need to require the built-in
Buffer
module in Node.js. This module provides a way to create and manipulate binary data.Next, you can use the
Buffer.from()
method to create a new buffer from the input string. Pass the string as the first argument and specify the encoding as the second argument. In this case, you would use'utf-8'
as the encoding since most strings are encoded in UTF-8.After creating the buffer, you can use the
toString()
method with'base64'
as the encoding to convert it to a Base64 string. This method returns the Base64 representation of the buffer.
Here's an example code snippet that demonstrates the steps:
const Buffer = require('buffer').Buffer;
const stringToConvert = 'Hello, World!';
const buffer = Buffer.from(stringToConvert, 'utf-8');
const base64String = buffer.toString('base64');
console.log(base64String);
In the example above, the input string 'Hello, World!'
is converted to a Base64 string. The resulting Base64 string is then logged to the console.
Please note that the Buffer
module is built-in and does not require any additional installation or dependencies in Node.js.