TextEncoder / TextDecoder:UTF-8(或其它)和字节之间的互转。
const bytes = new TextEncoder().encode("hello"); // Uint8Array
const str = new TextDecoder().decode(bytes); // "hello"
TextEncoder().encode(...)
const secretBytes = new TextEncoder().encode(process.env.JWT_SECRET);
步骤 | 说明 |
---|---|
new TextEncoder() |
浏览器/Node 全局类,默认 UTF-8。 |
.encode(string) |
将 JS 字符串按 UTF-8 编码为 Uint8Array。 |
结果 | 每个 UTF-8 字节占一项,便于后续加密、写文件等二进制场景。 |