📜  atob nodejs - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:31.675000             🧑  作者: Mango

Atob Nodejs - Javascript

The atob function is a built-in function in JavaScript that decodes a string of data which has been encoded using base-64 encoding. In Node.js, this function can also be used by using the Buffer class as shown below:

const base64EncodedString = 'SGVsbG8gV29ybGQh';
const Buffer = require('buffer').Buffer;
const decodedData = Buffer.from(base64EncodedString, 'base64').toString();
console.log(decodedData); // Hello World!

Here, we first define a base64 encoded string, then we require the buffer module and use the Buffer.from method to decode the string. We pass the encoding type as the second parameter to the method and then convert the buffer to a string using the toString method. The decoded string is then logged to the console.

In the browser, you can use the atob function in a similar way:

const base64EncodedString = 'SGVsbG8gV29ybGQh';
const decodedData = window.atob(base64EncodedString);
console.log(decodedData); // Hello World!

Here, we use the window.atob method to decode the base64 encoded string.

In both cases, the decoded string should match the original string that was encoded using base64 encoding.

Conclusion

In summary, the atob function is a useful function in JavaScript that allows you to easily decode a string that has been encoded using base64 encoding. This function can be used in both Node.js and the browser, making it a versatile function for web developers to use.