[英]Convert a string to base64 in JavaScript. btoa and atob are deprecated
I have been working on some projects in VS Code lately and suddenly started receiving notifications in my code that btoa and atob are now deprecated.我最近一直在 VS Code 中处理一些项目,突然开始在我的代码中收到通知,说 btoa 和 atob 现在已弃用。 I can't find any resource for this besides VS Code.
除了 VS Code,我找不到任何资源。 If this is true, what alternative is there?
如果这是真的,还有什么选择?
btoa
and atob
are only deprecated for Node JS. btoa
和atob
仅在 Node JS 中被弃用。 If you prepend the window.
如果您预先
window.
you will get rid of this deprecation mark.您将摆脱此弃用标记。
On the other hand, if you are trying to use btoa o atob in the back-end side, you definitely should use Buffer
interface.另一方面,如果您尝试在后端使用 btoa o atob,则绝对应该使用
Buffer
接口。
References:参考:
Still within VS Code, I had a look into the comments for the deprecated btoa(str) function.仍然在 VS Code 中,我查看了已弃用的 btoa(str) 函数的注释。 It suggests the following as a replacement:
它建议将以下内容作为替代:
const base64Str = Buffer.from(str, 'utf8').toString('base64');
I am using the follow methods below to encode/decode base64 in modern Javascript ES6.我正在使用以下方法在现代 Javascript ES6 中对 base64 进行编码/解码。 It's nice to wrap these methods in a js utils file, so it's easy to just import them and use.
将这些方法包装在一个 js utils 文件中很好,因此只需导入它们并使用它们就很容易。
export const encodeBase64 = (data) => {
return Buffer.from(data).toString('base64');
}
export const decodeBase64 = (data) => {
return Buffer.from(data, 'base64').toString('ascii');
}
The Node btoa() and atob() functions are the only ones that have been deprecated. Node btoa() 和 atob() 函数是唯一被弃用的函数。 However, if you're working on the DOM code (front-end) and see this deprecated notice, you can use the window object to get around it.
但是,如果您正在处理 DOM 代码(前端)并看到此弃用通知,则可以使用 window 对象来绕过它。
window.atob()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.