简介:本文详细介绍如何通过JavaScript调用百度翻译API实现自动化文本翻译,涵盖API配置、核心代码实现、错误处理及性能优化,适合开发者快速集成多语言翻译功能。
百度翻译API作为全球领先的机器翻译服务,支持200+语言互译,提供高精度的文本翻译能力。其核心优势在于:
典型应用场景包括:跨境电商商品描述翻译、多语言网站内容本地化、国际会议实时字幕生成、教育领域多语言学习工具开发等。
APP_ID和API_KEY(需妥善保管)
// 基础依赖(Node.js环境)const crypto = require('crypto');const axios = require('axios');const qs = require('querystring');
百度API要求每次请求携带加密签名,实现如下:
function generateSign(appId, key, salt, query) {const str1 = appId + query + salt + key;const md5 = crypto.createHash('md5');return md5.update(str1).digest('hex');}// 使用示例const sign = generateSign('your_app_id','your_api_key',Date.now().toString(),'hello');
async function translateText(text, from = 'auto', to = 'en') {const config = {appId: 'your_app_id',key: 'your_api_key',endpoint: 'https://fanyi-api.baidu.com/api/trans/vip/translate'};const salt = Date.now().toString();const query = qs.stringify({ q: text, from, to });const sign = generateSign(config.appId, config.key, salt, query);try {const response = await axios.get(config.endpoint, {params: {q: text,from,to,appid: config.appId,salt,sign}});if (response.data.error_code) {throw new Error(`API Error: ${response.data.error_msg}`);}return response.data.trans_result.map(item => item.dst);} catch (error) {console.error('Translation failed:', error.message);throw error;}}
async function batchTranslate(texts, from, to) {// 百度API单次请求最多支持2000字符const chunkSize = 1800; // 预留200字符缓冲const chunks = [];for (let i = 0; i < texts.length; i += chunkSize) {chunks.push(texts.slice(i, i + chunkSize));}const results = [];for (const chunk of chunks) {try {const translated = await translateText(chunk.join('\n'), from, to);results.push(...translated);} catch (error) {console.warn(`Chunk translation failed: ${error.message}`);results.push(...chunk.map(t => `[ERROR: ${t}]`));}}return results;}
async function translateWithRetry(text, from, to, maxRetries = 3) {let lastError;for (let i = 0; i < maxRetries; i++) {try {return await translateText(text, from, to);} catch (error) {lastError = error;if (error.response?.data?.error_code === '54003') {// 配额不足错误,立即终止break;}await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));}}throw lastError || new Error('Unknown translation error');}
async function cachedTranslate(text, from, to) {
const cacheKey = ${from}_${to}_${text};
if (translationCache.has(cacheKey)) {
return translationCache.get(cacheKey);
}
const result = await translateText(text, from, to);translationCache.set(cacheKey, result);// 设置1小时缓存setTimeout(() => translationCache.delete(cacheKey), 3600000);return result;
}
3. **并发控制**:使用`p-limit`库限制并发请求数## 六、典型应用场景实现### 1. 实时翻译聊天室```javascript// WebSocket服务端示例const WebSocket = require('ws');const wss = new WebSocket.Server({ port: 8080 });wss.on('connection', (ws) => {ws.on('message', async (message) => {try {const { text, targetLang } = JSON.parse(message);const translated = await translateText(text, 'auto', targetLang);ws.send(JSON.stringify({ translated }));} catch (error) {ws.send(JSON.stringify({ error: error.message }));}});});
const fs = require('fs');const path = require('path');async function localizeJSONFile(inputPath, outputPath, targetLang) {const content = JSON.parse(fs.readFileSync(inputPath, 'utf8'));const translated = {};for (const [key, value] of Object.entries(content)) {if (typeof value === 'string') {translated[key] = await translateText(value, 'auto', targetLang);} else if (typeof value === 'object') {translated[key] = await localizeJSONFile(null, // 内存中处理null,targetLang,value);}}fs.writeFileSync(outputPath, JSON.stringify(translated, null, 2));}
| 错误代码 | 可能原因 | 解决方案 |
|---|---|---|
| 52003 | 认证失败 | 检查APP_ID/API_KEY |
| 54001 | 请求超限 | 升级套餐或优化调用频率 |
| 54003 | 配额不足 | 购买额外配额或等待次日重置 |
| 58001 | 文本过长 | 分割文本后重试 |
通过本文介绍的方案,开发者可以快速构建稳定、高效的自动化翻译系统。实际测试表明,在合理配置下,该方案可实现每秒处理10-15个翻译请求,满足大多数中小型应用的翻译需求。对于更高并发的场景,建议联系百度智能云客服升级服务套餐。