How can I do Base64 encoding in Node.js?
In Node.js, you can use the built-in Buffer
class to perform Base64 encoding and decoding. The Buffer
class provides methods for encoding and decoding data in various formats, including Base64.
Here's an example of how to perform Base64 encoding:
// Convert a string to Base64
const originalString = 'Hello, this is a string to encode!';
const base64String = Buffer.from(originalString).toString('base64');
console.log('Original String:', originalString);
console.log('Base64 Encoded:', base64String);
In this example:
- The
Buffer.from(originalString)
method creates aBuffer
object from the original string. - The
toString('base64')
method converts theBuffer
object to a Base64-encoded string.
If you want to decode a Base64 string back to its original form, you can use the following:
// Convert a Base64 string back to the original string
const decodedString = Buffer.from(base64String, 'base64').toString('utf-8');
console.log('Base64 Decoded:', decodedString);
In this example:
- The
Buffer.from(base64String, 'base64')
method creates aBuffer
object from the Base64-encoded string. - The
toString('utf-8')
method converts theBuffer
object to a UTF-8 encoded string, representing the original string.
These methods are synchronous. If you're working with asynchronous code or need to handle binary data in streams, you may want to explore additional methods provided by the Buffer
class or consider using third-party libraries such as base64url
or btoa
(for browsers).
-
How do I pass command line arguments to a Node.js program and receive them?
In Node.js, you can pass command line arguments to your script the same as you would for any other command line application. Simply type your arguments after the script path separated with a space ...
Questions -
How to get `GET` variables in Express.js on Node.js?
In Express.js, you can access GET (query string) variables using the req.query object. The req.query object contains key-value pairs of the query string parameters in a GET request. Here's an examp...
Questions -
How to reduce size of node_modules folder?
Reducing the size of the node_modules folder in a Node.js project can be important, especially when deploying applications or managing version control. Here are several strategies you can use to mi...
Questions
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github