JavaScript/TypeScript SDK

JavaScript/TypeScript SDK

Official JavaScript and TypeScript client library for TranslatePlus API - Professional translation service for text, HTML, emails, subtitles, and i18n files in 100+ languages.

Package Information

Package: translateplus-js
Version: 2.0.1+ (Production/Stable)
Node.js Support: Node.js 18+
License: MIT

Official Repositories

Installation

npm install translateplus-js

Or with yarn:

yarn add translateplus-js

Quick Start

import { TranslatePlusClient } from 'translateplus-js';
 
// Initialize client
const client = new TranslatePlusClient({
  apiKey: 'your-api-key'
});
 
// Translate a single text
const result = await client.translate({
  text: 'Hello, world!',
  source: 'en',
  target: 'fr'
});
console.log(result.translations.translation);
// Output: "Bonjour le monde !"
 
// Translate multiple texts
const texts = ['Hello', 'Goodbye', 'Thank you'];
const batchResult = await client.translateBatch({
  texts: texts,
  source: 'en',
  target: 'fr'
});
batchResult.translations.forEach(translation => {
  console.log(translation.translation);
});

Features

  • Full API Support - All endpoints including text, batch, HTML, email, subtitles, and i18n translation
  • TypeScript Support - Full type definitions for TypeScript projects
  • Concurrent Requests - Built-in support for parallel translations with configurable concurrency limits
  • Error Handling - Comprehensive exception handling with detailed error messages
  • Retry Logic - Automatic retry with exponential backoff for failed requests
  • Module Support - Both ESM and CommonJS module formats supported
  • 100+ Languages - Support for all languages available in TranslatePlus

API Reference

Client Configuration

import { TranslatePlusClient } from 'translateplus-js';
 
const client = new TranslatePlusClient({
  apiKey: 'your-api-key',                    // Required: Your TranslatePlus API key
  baseUrl: 'https://api.translateplus.io',   // Optional: API base URL
  timeout: 30000,                            // Optional: Request timeout in milliseconds (default: 30000)
  maxRetries: 3,                              // Optional: Maximum retries (default: 3)
  maxConcurrent: 5                            // Optional: Max concurrent requests (default: 5)
});

Translation Methods

Translate Text

const result = await client.translate({
  text: 'Hello, world!',
  source: 'en',  // Optional, defaults to 'auto'
  target: 'fr'   // Required
});
console.log(result.translations.translation);

Batch Translation

const texts = ['Hello', 'Goodbye', 'Thank you'];
const result = await client.translateBatch({
  texts: texts,
  source: 'en',
  target: 'fr'
});
result.translations.forEach(translation => {
  console.log(translation.translation);
});

Translate HTML

const html = '<p>Hello <b>world</b></p>';
const result = await client.translateHTML({
  html: html,
  source: 'en',
  target: 'fr'
});
console.log(result.html);  // "<p>Bonjour <b>monde</b></p>"

Translate Email

const result = await client.translateEmail({
  subject: 'Welcome',
  emailBody: '<p>Thank you for signing up!</p>',
  source: 'en',
  target: 'fr'
});
console.log(result.subject);     // "Bienvenue"
console.log(result.htmlBody);    // "<p>Merci de vous être inscrit!</p>"

Translate Subtitles

const subtitleContent = "1\n00:00:01,000 --> 00:00:02,000\nHello world\n";
const result = await client.translateSubtitles({
  content: subtitleContent,
  format: 'srt',  // or 'vtt'
  source: 'en',
  target: 'fr'
});
console.log(result.content);

Language Methods

Detect Language

const result = await client.detectLanguage('Bonjour le monde');
console.log(result.languageDetection.language);     // "fr"
console.log(result.languageDetection.confidence);   // 0.95

Get Supported Languages

const result = await client.getSupportedLanguages();
const languages = result.supportedLanguages;
Object.entries(languages).forEach(([name, code]) => {
  console.log(`${name}: ${code}`);
});

Account Methods

Get Account Summary

const summary = await client.getAccountSummary();
console.log(`Credits remaining: ${summary.creditsRemaining}`);
console.log(`Plan: ${summary.planName}`);
console.log(`Concurrency limit: ${summary.concurrencyLimit}`);

i18n Translation Jobs

Create i18n Job

const result = await client.createI18nJob({
  filePath: '/path/to/locales/en.json',
  targetLanguages: ['fr', 'es', 'de'],
  sourceLanguage: 'en',
  webhookUrl: 'https://example.com/webhook'  // Optional
});
console.log(`Job ID: ${result.jobId}`);

Get Job Status

const status = await client.getI18nJobStatus('job-123');
console.log(`Status: ${status.status}`);      // "pending", "processing", "completed", "failed"
console.log(`Progress: ${status.progress}%`);   // Percentage

List Jobs

const jobs = await client.listI18nJobs({
  page: 1,
  pageSize: 20
});
jobs.results.forEach(job => {
  console.log(`Job ${job.id}: ${job.status}`);
});

Error Handling

The client throws specific exceptions for different error types:

import {
  TranslatePlusError,
  TranslatePlusAPIError,
  TranslatePlusAuthenticationError,
  TranslatePlusRateLimitError,
  TranslatePlusInsufficientCreditsError,
  TranslatePlusValidationError
} from 'translateplus-js';
 
try {
  const result = await client.translate({ text: 'Hello', target: 'fr' });
} catch (error) {
  if (error instanceof TranslatePlusAuthenticationError) {
    console.error('Authentication failed:', error.message);
    console.error('Status code:', error.statusCode);
  } else if (error instanceof TranslatePlusInsufficientCreditsError) {
    console.error('Insufficient credits:', error.message);
  } else if (error instanceof TranslatePlusRateLimitError) {
    console.error('Rate limit exceeded:', error.message);
  } else if (error instanceof TranslatePlusAPIError) {
    console.error('API error:', error.message);
    console.error('Status code:', error.statusCode);
    console.error('Response:', error.response);
  } else if (error instanceof TranslatePlusValidationError) {
    console.error('Validation error:', error.message);
  } else {
    console.error('Error:', error.message);
  }
}

Advanced Usage

Concurrent Translations

The client automatically handles concurrency limits. You can configure the maximum concurrent requests:

const client = new TranslatePlusClient({
  apiKey: 'your-api-key',
  maxConcurrent: 10  // Allow up to 10 concurrent requests
});

Custom Timeout and Retries

const client = new TranslatePlusClient({
  apiKey: 'your-api-key',
  timeout: 60000,      // 60 second timeout
  maxRetries: 5        // Retry up to 5 times
});

TypeScript Usage

The package includes full TypeScript type definitions:

import { TranslatePlusClient, TranslateResult } from 'translateplus-js';
 
const client = new TranslatePlusClient({
  apiKey: 'your-api-key'
});
 
const result: TranslateResult = await client.translate({
  text: 'Hello',
  source: 'en',
  target: 'fr'
});

Requirements

  • Node.js 18 or higher
  • npm or yarn for package management

Resources

License

MIT License - see LICENSE (opens in a new tab) file for details.