Constructor

Translate

new Translate(options)

With Google Translate, you can dynamically translate text between thousands of language pairs.

The Google Translate API lets websites and programs integrate with Google Translate programmatically.

Parameter

options

Optional

ClientConfig

Configuration options.

See also

Getting Started

Identifying your application to Google

Example

//-
// <h3>Custom Translate API</h3>
//
// The environment variable, `GOOGLE_CLOUD_TRANSLATE_ENDPOINT`, is honored as
// a custom backend which our library will send requests to.
//-

Full quickstart example:

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const translate = new Translate({
  projectId: projectId,
});

// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';

// Translates some text into Russian
translate
  .translate(text, target)
  .then(results => {
    const translation = results[0];

    console.log(`Text: ${text}`);
    console.log(`Translation: ${translation}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Methods

detect

detect(input, callback) returns Promise containing DetectResponse

Detect the language used in a string or multiple strings.

Parameter

input

(string or Array of string)

The source string input.

callback

Optional

DetectCallback

Callback function.

See also

Detect Language

Returns

Promise containing DetectResponse 

Example

const Translate = require('@google-cloud/translate');

const translate = new Translate();

//-
// Detect the language from a single string input.
//-
translate.detect('Hello', function(err, results) {
  if (!err) {
    // results = {
    //   language: 'en',
    //   confidence: 1,
    //   input: 'Hello'
    // }
  }
});

//-
// Detect the languages used in multiple strings. Note that the results are
// now provied as an array.
//-
translate.detect([
  'Hello',
  'Hola'
], function(err, results) {
  if (!err) {
    // results = [
    //   {
    //     language: 'en',
    //     confidence: 1,
    //     input: 'Hello'
    //   },
    //   {
    //     language: 'es',
    //     confidence: 1,
    //     input: 'Hola'
    //   }
    // ]
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
translate.detect('Hello').then(function(data) {
  var results = data[0];
  var apiResponse = data[2];
});

Here's a full example:

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const text = 'The text for which to detect language, e.g. Hello, world!';

// Detects the language. "text" can be a string for detecting the language of
// a single piece of text, or an array of strings for detecting the languages
// of multiple texts.
translate
  .detect(text)
  .then(results => {
    let detections = results[0];
    detections = Array.isArray(detections) ? detections : [detections];

    console.log('Detections:');
    detections.forEach(detection => {
      console.log(`${detection.input} => ${detection.language}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

getLanguages

getLanguages(target, callback) returns Promise containing GetLanguagesResponse

Get an array of all supported languages.

Parameter

target

Optional

string

Get the language names in a language other than English.

callback

Optional

GetLanguagesCallback

Callback function.

See also

Discovering Supported Languages

Returns

Promise containing GetLanguagesResponse 

Examples

Gets the language names in English:

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

// Lists available translation language with their names in English (the default).
translate
  .getLanguages()
  .then(results => {
    const languages = results[0];

    console.log('Languages:');
    languages.forEach(language => console.log(language));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Gets the language names in a langauge other than English:

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const target = 'The target language for language names, e.g. ru';

// Lists available translation language with their names in a target language
translate
  .getLanguages(target)
  .then(results => {
    const languages = results[0];

    console.log('Languages:');
    languages.forEach(language => console.log(language));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

translate

translate(input, options, callback) returns Promise containing TranslateResponse

Translate a string or multiple strings into another language.

Parameter

input

(string or Array of string)

The source string input.

options

Optional

(string or TranslateRequest)

If a string, it is interpreted as the target ISO 639-1 language code to translate the source input to. (e.g. en for English). If an object, you may also specify the source language.

callback

Optional

TranslateCallback

Callback function.

See also

Translate Text

Throws

Error 

If options is provided as an object without a to property.

Returns

Promise containing TranslateResponse 

Example

//-
// Pass a string and a language code to get the translation.
//-
translate.translate('Hello', 'es', function(err, translation) {
  if (!err) {
    // translation = 'Hola'
  }
});

//-
// The source language is auto-detected by default. To manually set it,
// provide an object.
//-
var options = {
  from: 'en',
  to: 'es'
};

translate.translate('Hello', options, function(err, translation) {
  if (!err) {
    // translation = 'Hola'
  }
});

//-
// Translate multiple strings of input. Note that the results are
// now provied as an array.
//-
var input = [
  'Hello',
  'How are you today?'
];

translate.translate(input, 'es', function(err, translations) {
  if (!err) {
    // translations = [
    //   'Hola',
    //   'Como estas hoy?'
    // ]
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
translate.translate('Hello', 'es').then(function(data) {
  var translation = data[0];
  var apiResponse = data[1];
});

Full translation example:

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';

// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
translate
  .translate(text, target)
  .then(results => {
    let translations = results[0];
    translations = Array.isArray(translations)
      ? translations
      : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Translation using the premium model:

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';
// const model = 'The model to use, e.g. nmt';

const options = {
  // The target language, e.g. "ru"
  to: target,
  // Make sure your project is whitelisted.
  // Possible values are "base" and "nmt"
  model: model,
};

// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
translate
  .translate(text, options)
  .then(results => {
    let translations = results[0];
    translations = Array.isArray(translations)
      ? translations
      : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });