Skip to content

引入

ts
import {
  decode,
  innerDecode,
  encode,
  innerEncode
} from 't-comm';

// 不支持 tree-shaking 的项目
import {
  decode,
  innerDecode,
  encode,
  innerEncode
} from 't-comm/lib/base64/index';

// 只支持 ESM 的项目
import {
  decode,
  innerDecode,
  encode,
  innerEncode
} from 't-comm/es/base64/index';

decode

描述

将 Base64 编码的字符串解码为原始字符串 支持 Unicode 字符(包括中文、emoji 等),兼容小程序环境

参数

参数名描述
str

Base64 编码的字符串

返回:

解码后的原始字符串

示例

ts
decode('SGVsbG8gV29ybGQ='); // 'Hello World'
decode('5L2g5aW95LiW55WM'); // '你好世界'
decode('8J+YgA=='); // '😀'

innerDecode

描述

Base64 解码的内部实现(小程序版本的 atob) 将 Base64 编码的字符串解码为 Latin1 字符串

Throws:

  • TypeError

    当输入不是有效的 Base64 字符串时抛出错误

参数

参数名描述
string

Base64 编码的字符串

返回:

解码后的字符串

示例

ts
innerDecode('SGVsbG8='); // 'Hello'

encode

描述

将字符串编码为 Base64 格式 支持 Unicode 字符(包括中文、emoji 等),兼容小程序环境

参数

参数名描述
str

要编码的字符串

返回:

Base64 编码后的字符串

示例

ts
encode('Hello World'); // 'SGVsbG8gV29ybGQ='
encode('你好世界'); // '5L2g5aW95LiW55WM'
encode('😀'); // '8J+YgA=='

innerEncode

描述

Base64 编码的内部实现(小程序版本的 btoa) 将 Latin1 范围内的字符串编码为 Base64

Throws:

  • TypeError

    当字符串包含 Latin1 范围外的字符时抛出错误

参数

参数名描述
string

要编码的字符串(仅支持 Latin1 字符)

返回:

Base64 编码后的字符串

示例

ts
innerEncode('Hello'); // 'SGVsbG8='