Google Translation API for Deno🛠️

Features

  • Automatic language detection with default options.
  • Option to specify source and target languages.
  • Choice of translation models and clients for different response data.
  • Customizable Google Translate URL.
  • Error handling for common translation issues.
  • Modern ESM module instead of CommonJS.

Usage

[!NOTE] Only ESM module is supported.

Import

Deno:

import { Translator } from "https://deno.land/x/translator/mod.ts";

ESM:

import { Translator } from 'https://esm.sh/@fwqaaq/translator'

or:

pnpm add @fwqaaq/translator

Example

const options = {
  source: "zh-CN",
  model: 't',
  client: 'gtx',
  url: 'https://translate.googleapis.com/translate_a/'
};

async function main() {
  const translator = new Translator('你好', options);
  const response = await translator.translate();
  console.log(response) // { lang: 'zh-CN', text: 'Hello' }
}

main()

API Reference

  • Constructor
    • text: string - The source text to be translated.
    • options: TranslateOptions - (Optional) The options to use when translating.
  • Methods
    • translate(isRaw: boolean): Promise<ResponseData | Array<any>> - Translates the text. If isRaw is true, returns raw response data. Default is false.
    • audio(isOriginal: boolean): Promise<blob> - Returns the blob. If isOriginal is true, using the original text to generate the audio. Default is false.
  • TranslateOptions Interface
    • source: string - Source language (default: 'auto').
    • target: string - Target language (default: 'en').
    • model: 't' | 'single' - Translation model (default: 't').
    • client: 'gtx' | 'dict-chrome-ex' - Client for translation (default: 'gtx').
    • url: string - Google Translate URL (default: 'https://clients5.google.com/translate_a/').
  • ResponseData Interface
    • lang: string - The language of the source text.
    • text: string - The translated text.