Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
JavaScript translation libraries convert text from one human language to another from Node.js, the browser, or React Native. A client sends each string to a hosted machine translation API and receives the translated text with its detected source language. These libraries let apps and AI agents serve content in a reader's own language.
Popularity
Google Cloud Translate has the most monthly downloads among dedicated translation clients in this comparison, at 2.8M.
import { pipeline } from '@huggingface/transformers';
const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {
src_lang: 'hin_Deva', // Hindi
tgt_lang: 'fra_Latn', // French
});
// [{ translation_text: 'La vie est comme une boîte à chocolat.' }]
async (event) => {
// Retrieve the translation pipeline. When called for the first time, // this will load the pipeline and save it for future use. const translator = await MyTranslationPipeline.getInstance((x) => {
// We also add a progress callback to the pipeline so that we can // track model loading. self.postMessage(x);
});
// Capture partial output as it streams from the pipeline const streamer = new TextStreamer(translator.tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
callback_function: function (text) {
self.postMessage({
status: "update",
output: text,
});
},
});
// Actually perform the translation const output = await translator(event.data.text, {
tgt_lang: event.data.tgt_lang,
src_lang: event.data.src_lang,
// Allows for partial output streamer,
});
// Send the output back to the main thread self.postMessage({
status: "complete",
output,
});
}
@google-cloud/translate
Provides Node.js clients for Google Cloud text and document translation.
Downloads / mo
2.8M
Stars
3.2K
Last release
10.3.0
License
Apache-2.0
Strengths
Translates formatted documents.Use the Advanced client for document translation.
Uses custom translation terminology.Apply a glossary to Advanced document translation.
Limitations
Mixed PDFs skip scanned content.Scanned content stays untranslated in PDFs containing both scanned and native text.
Requires a billed cloud project.Enable Cloud Translation and billing before authenticating the client.
async function updateTranslations() {
try {
const root = "./app/localization/locales";
const fromLanguage = "en";
// Get valid languages from Google Translate API let [googleLanguages] = await translate.getLanguages(); // ie. { code: "en", name: "English" }
googleLanguages = googleLanguages.map(gl => gl.code.replace("-", "_"))
// Uncomment me to view the various languages Google can translate to/from //console.log(googleLanguages); // Get all language directories; // https://stackoverflow.com/a/35759360/1837080 const getDirectories = p => readdirSync(p).filter(f => statSync(join(p, f)).isDirectory());
const languageDirectories = getDirectories(root).filter(d => googleLanguages.includes(d));
// For each language, read in any missing translations // and translate for (const languageDirectory of languageDirectories) {
// Check to make sure each language has the proper files try {
const languageRoot = `${root}/${languageDirectory}`;
const translationFile = `${languageRoot}/translation.json`;
const missingTranslationFile = `${languageRoot}/translation.missing.json`;
const translationExists = fs.existsSync(translationFile);
const translationMissingExists = fs.existsSync(missingTranslationFile);
if (translationExists && translationMissingExists) {
// Read in contents of files const translations = JSON.parse(fs.readFileSync(translationFile, {
encoding: "utf8"
}));
const missing = JSON.parse(fs.readFileSync(missingTranslationFile, {
encoding: "utf8"
}));
// Only translate files with actual values const missingKeys = Object.keys(missing);
if (missingKeys.length > 0){
// Translate each of the missing keys to the target language for (const missingKey of missingKeys){
const googleTranslation = await translate.translate(missingKey, {
from: fromLanguage,
to: languageDirectory
});
// Only set if a value is returned if (googleTranslation.length > 0){
translations[missingKey] = googleTranslation[0];
}
}
// Write output back to file fs.writeFileSync(translationFile, JSON.stringify(translations, null, 2));
fs.writeFileSync(missingTranslationFile, JSON.stringify({}, null, 2));
console.log(`Successfully updated translations for ${languageDirectory}`);
} else {
console.log(`Skipped creating translations for ${languageDirectory}; none found!`);
}
} else {
// Log if we failed if (!translationExists) {
console.error(`Could not generate translations for language '${languageDirectory}' because ${translationFile} does not exist, skipping!`);
} else if (!translationMissingExists) {
console.error(`Could not generate translations for language '${languageDirectory}' because ${missingTranslationFile} does not exist, skipping!`);
}
}
} catch (error) {
console.error("Failed due to fatal error");
console.error(error);
}
}
} catch (e) {
console.error("Failed due to fatal error");
console.error(e);
}
}
@aws-sdk/client-translate
Provides the AWS Translate client for Node.js, browsers, and React Native.
import * as deepl from "deepl-node";
const client = new deepl.DeepLClient(process.env.DEEPL_AUTH_KEY);
const result = await client.translateText("Hello, world!", null, "fr");
console.log(result.text);
@azure-rest/ai-translation-text
Provides an isomorphic client for the Azure Translator service.
async function autoTranslate() {
const sourceOfTruth = await glob('**/*.json', {
cwd: sourceRoot,
});
const targetLanguages = (await fs.readdir(langRoot)).filter((file) => file !== 'en')
console.log('Found source of truth files: ', sourceOfTruth);
console.log(`Found ${targetLanguages.length} target languages `);
sourceOfTruth.map(async (file) => {
// Load the file contents const source = await fs.readFile(path.join(sourceRoot, file), 'utf8');
const sourceObj = JSON.parse(source);
// This flattens the potentially nested object into a single level const keys = deepKeys(sourceObj);
// Attempt to translate target languages await Promise.all(targetLanguages.map(async (lang) => {
let existing = {};
try {
const existingFile = await fs.readFile(path.join(langRoot, lang, file), 'utf8');
existing = JSON.parse(existingFile);
} catch (err) {
// Assume it doesn't exist existing = {};
}
const initial = Promise.resolve(existing);
const completed = await keys.reduce(async (acc, key) => {
const newAcc = await acc;
if (hasProperty(newAcc, key)) {
// Already translated return newAcc;
}
const value = getProperty(sourceObj, key);
// Check if the value contains double braces with interpolation placeholders const hasInterpolation = /\{\{([^{}]+?)\}\}/.test(value);
if (hasInterpolation) {
// Extract the interpolation placeholders and preserve the braces const placeholders = value.match(/\{\{([^{}]+?)\}\}/g);
// Replace the interpolation placeholders with a placeholder token const placeholderToken = '__PLACEHOLDER__';
const replacedValue = value.replace(/\{\{([^{}]+?)\}\}/g, placeholderToken);
// Translate the replaced value // @ts-ignore const translated = await translate(replacedValue, { from: 'en', to: lang });
// Restore the interpolation placeholders using the placeholder token const translatedValue = placeholders.reduce((acc, placeholder) => {
return acc.replace(placeholderToken, placeholder);
}, translated);
setProperty(newAcc, key, translatedValue);
} else {
try { // @ts-ignore
const translated = await translate(value, { from: 'en', to: lang });
setProperty(newAcc, key, translated);
} catch (err) {
console.log(`Failed to translate ${key} in ${file} to ${lang}`);
}
}
return newAcc
}, initial);
await fs.writeFile(path.join(langRoot, lang, file), `${JSON.stringify(completed, null, 2)}\n`);
}));
});
}
FAQ
Google Cloud Translate suits apps that need text and document translation on Google Cloud. DeepL suits apps that translate documents and want glossary support. Transformers.js suits apps that must translate on the device without a server.
Install @google-cloud/translate and create a client with a Google Cloud project's credentials. The client's translate method takes the text and a target language code.
The DeepL API is a paid machine translation service with a free tier. DeepL provides its official Node.js client for text and document translation.
DeepL supports fewer languages and adds glossaries and formality control. Google Cloud Translate covers more languages and supports custom models on Google Cloud.
google-translate-api-x and bing-translate-api call the free web translators without an API key. Both rely on unofficial endpoints that can change or rate-limit requests without notice.
The Azure Translator client is an isomorphic REST client for Node.js and the browser. It authenticates with an Azure resource key and region.
For coding agents
Found your translation library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.