ZBLOG

vite + vue + Typescript base64编解码

在 Vite + Vue + TypeScript 中,你可以使用 btoaatob 函数进行 Base64 编解码。

Base64 编码是一种将二进制数据转换为 ASCII 字符串的编码方式,常用于在文本环境中传输或存储二进制数据。

示例:将字符串进行 Base64 编码

const originalText = 'Hello, World!';
const encodedText = btoa(originalText);
console.log(encodedText); // 输出:SGVsbG8sIFdvcmxkIQ==

上述示例中,我们使用 btoa 函数对原始字符串 "Hello, World!" 进行 Base64 编码。编码后的结果是 "SGVsbG8sIFdvcmxkIQ=="

示例:将 Base64 编码的字符串进行解码

const encodedText = 'SGVsbG8sIFdvcmxkIQ==';
const decodedText = atob(encodedText);
console.log(decodedText); // 输出:Hello, World!

上述示例中,我们使用 atob 函数对经过 Base64 编码的字符串 "SGVsbG8sIFdvcmxkIQ==" 进行解码。解码后得到原始字符串 "Hello, World!"

需要注意的是,在浏览器环境下,这两个函数是全局对象 window 的方法;在 Node.js 环境下,则可以通过引入 'buffer' 模块来使用相应的函数。

例如,在 Node.js 环境下对字符串进行 Base64 编解码:

import { Buffer } from 'buffer';

const originalText = 'Hello, World!';
const encodedText = Buffer.from(originalText).toString('base64');
console.log(encodedText); // 输出:SGVsbG8sIFdvcmxkIQ==

const decodedText = Buffer.from(encodedText, 'base64').toString();
console.log(decodedText); // 输出:Hello, World!

这里我们使用 Buffer 对象的静态方法 from 和实例方法 toString 进行 Base64 编解码。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16783

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?