编码
服务端 Studio 脚本中使用 Node 内置 API 处理编码。Base64 和字节长度优先使用 Buffer,尤其是文本可能包含中文或其他非 ASCII 内容时。
常用方法
| 方法 | 说明 |
|---|---|
Buffer.from(value, 'utf8') | 把 UTF-8 文本转换为字节;文本转 Base64 前使用 |
Buffer.from(value, 'base64') | 把 Base64 内容转换回字节;Base64 转文本前使用 |
.toString('base64') | 把字节编码为 Base64 文本 |
.toString('utf8') | 把字节解码为 UTF-8 文本 |
Buffer.byteLength(value, 'utf8') | 获取文本字节长度;外部接口需要内容大小时使用 |
new URLSearchParams() | 构造 application/x-www-form-urlencoded 请求体 |
URLSearchParams.set(name, value) | 设置一个表单值;同名字段会覆盖旧值 |
URLSearchParams.append(name, value) | 为同名字段追加一个值 |
encodeURIComponent(value) | 编码一个 URL query 字段值 |
文本转 Base64
import { Buffer } from 'node:buffer';
const text = 'orderNo,amount\nSO-1001,1200\n';
const contentBase64 = Buffer.from(text, 'utf8').toString('base64');
const size = Buffer.byteLength(text, 'utf8');
Base64 转文本
import { Buffer } from 'node:buffer';
const text = Buffer.from(contentBase64, 'base64').toString('utf8');
创建 URL-Encoded 请求体
const body = new URLSearchParams();
body.set('name', 'SO-1001');
body.set('amount', '1200');
await context.http.requestJson({
url: 'https://example.com/api/orders',
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
body,
});
编码单个 URL 值
const keyword = encodeURIComponent('SO-1001 paid');
const url = `https://example.com/search?q=${keyword}`;
说明
不要把 btoa 作为业务文本的主要编码方式。中文或其他非 ASCII 内容请使用 Buffer.from(value, 'utf8').toString('base64')。