# node: tx
URL: https://generaltranslation.com/zh/docs/node/api/strings/tx.mdx
---
title: tx
description: tx runtime 字符串翻译函数 API 参考
---
## 概述
`tx` 函数会在 runtime 对字符串进行翻译。与解析 构建时 译文的 [`getGT`](/docs/node/api/get-gt) 不同,`tx` 会发送内容进行按需翻译,因此它可以翻译那些只有在 runtime 才能确定的字符串。
```js
import { tx } from 'gt-node';
const translated = await tx('Hello, world!');
```
**Runtime 翻译:**
`tx` 会按需翻译,这意味着相较于构建时翻译,需要发起网络请求,并会产生一定延迟。
对于在构建时即可确定的字符串,请使用 [`getGT`](/docs/node/api/get-gt);仅当内容是动态的或无法提前确定时,才使用 `tx`。
## 参考
### 参数
| 名称 | 类型 | 说明 |
| ---------- | ------------------------------------------------------------------------------- | ------------- |
| `content` | `string` | 要翻译的字符串。 |
| `options?` | [`RuntimeTranslationOptions`](/docs/next/api/types/runtime-translation-options) | 用于自定义翻译行为的选项。 |
### 返回值
`Promise` — 翻译后的字符串;如果无需翻译,则返回源字符串。
***
## 示例
### 基本用法
```js title="handler.js"
import { withGT, tx } from 'gt-node';
function handleRequest(locale) {
return withGT(locale, async () => {
return await tx('Processing complete');
});
}
```
### 使用变量
由于 `tx` 会在 runtime 翻译字符串,因此请使用模板字面量将变量直接嵌入字符串中。这样可确保发送去翻译的内容中包含变量值:
```js title="handler.js"
import { withGT, tx } from 'gt-node';
function handleStatus(locale, status) {
return withGT(locale, async () => {
return await tx(`Current status: ${status}`);
});
}
```
**`tx` 不会替换 `{variable}` 占位符。**
与使用 ICU 消息格式 (`{name}` 语法) 的 [`getGT`](/docs/node/api/get-gt) 不同,`tx` 会将该字符串视为普通字符串。
使用 JavaScript 模板字面量 (`` `Hello, ${name}` ``) 来插入变量。
### 使用上下文
添加 `$context` 以帮助消除译文中的歧义:
```js title="handler.js"
const translated = await tx('Spring', {
$context: 'the season, not a coil',
});
```
### 指定区域设置
覆盖通过 [`withGT`](/docs/node/api/with-gt) 设置的区域设置:
```js title="handler.js"
const translated = await tx('Hello, world!', { $locale: 'fr' });
```
***
## 注意事项
* `tx` 是异步的,会返回一个 Promise。请始终使用 `await` 等待结果。
* 翻译会在 runtime 通过网络请求进行,因此相比 构建时 翻译会有一定延迟。
* `tx` **不**支持 ICU `{variable}` 插值。请使用模板字面量嵌入变量。
* 对于带有 ICU 变量插值的静态字符串,使用 [`getGT`](/docs/node/api/get-gt) 或 [`msg`](/docs/node/api/strings/msg) / [`getMessages`](/docs/node/api/get-messages)。
## 下一步
* 如需了解构建时字符串翻译,请参阅 [`getGT`](/docs/node/api/get-gt)。
* 如需自定义翻译行为,请参阅 [`RuntimeTranslationOptions`](/docs/next/api/types/runtime-translation-options)。
* 如需比较各种翻译方式,请参阅 [字符串翻译模式](/docs/node/guides/strings)。