Skip to main content

Encoding

Use Node built-in APIs for encoding in server-side Studio scripts. Prefer Buffer for Base64 and byte length, especially when the text may contain non-ASCII characters.

Common Methods​

MethodDescription
Buffer.from(value, 'utf8')Converts UTF-8 text to bytes. Use this before Base64 encoding text
Buffer.from(value, 'base64')Converts Base64 content back to bytes. Use this before decoding Base64 text
.toString('base64')Encodes bytes as Base64 text
.toString('utf8')Decodes bytes as UTF-8 text
Buffer.byteLength(value, 'utf8')Gets the byte size of text. Use this when an API needs content size
new URLSearchParams()Builds application/x-www-form-urlencoded request bodies
URLSearchParams.set(name, value)Sets one form value. Repeated calls with the same name replace the old value
URLSearchParams.append(name, value)Appends another value for the same form name
encodeURIComponent(value)Encodes one value for use inside a URL query string

Base64 Encode Text​

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 Decode Text​

import { Buffer } from 'node:buffer';

const text = Buffer.from(contentBase64, 'base64').toString('utf8');

Create URL-Encoded Body​

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,
});

Encode One URL Value​

const keyword = encodeURIComponent('SO-1001 paid');
const url = `https://example.com/search?q=${keyword}`;

Notes​

Do not use btoa as the main business encoding method for text that may contain Chinese characters or other non-ASCII content. Use Buffer.from(value, 'utf8').toString('base64') instead.