Based on google-translate-api and google-translate-token
yarn add @liuli-util/google-translate-api-free
ref: node-example
yarn add @liuli-util/google-translate-api-free-nodejs-adapter
import { Translator } from '@liuli-util/google-translate-api-free'
import { TranslatorHandlerWithNodejs } from '@liuli-util/google-translate-api-free-nodejs-adapter'
const translator = new Translator(new TranslatorHandlerWithNodejs())
it('基本示例', async () => {
const res = await translator.translate('hello world', {
from: 'auto',
to: 'zh-cn',
})
console.log('res.text: ', res.text)
})
ref: browser-example
For cross origin requests it uses cors-anywhere
. You can use public cors-anywhere
server https://cors-anywhere.herokuapp.com/
or set up your own. By default it does not use proxying.
class TranslatorHandler implements ITranslatorHandler {
async handle<T>(url: string): Promise<T> {
return (await axios.get('http://cors-anywhere.herokuapp.com/' + url)).data
}
}
const translator = new Translator(new TranslatorHandler())
it('基本示例', async () => {
const res = await translator.translate('hello world', {
from: 'auto',
to: 'zh-cn',
})
console.log('res.text: ', res.text)
})
Type: string
The text to be translated
Type: object
Type: string
Default: auto
The text
language. Must be auto
or one of the codes/names (not case sensitive) contained
in languages.js
Type: string
Default: en
The language in which the text should be translated. Must be one of the codes/names (not case sensitive) contained in languages.js.
Type: boolean
Default: false
If true
, the returned object will have a raw
property with the raw response (string
) from Google Translate.
text
(string) – The translated text.from
(object)language
(object)didYouMean
(boolean) -true
if the API suggest a correction in the source languageiso
(string) - The code of the language that the API has recognized in thetext
text
(object)autoCorrected
(boolean) –true
if the API has auto corrected thetext
value
(string) – The auto correctedtext
or thetext
with suggested correctionsdidYouMean
(boolean) –true
if the API has suggested corrections to thetext
raw
(string) - Ifoptions.raw
is true, the raw response from Google Translate servers. Otherwise,''
.
Note that res.from.text
will only be returned if from.text.autoCorrected
or from.text.didYouMean
equals to true
.
In this case, it will have the corrections delimited with brackets ([ ]
):
translator
.translate('I spea Dutch')
.then((res) => {
console.log(res.from.text.value)
//=> I [speak] Dutch
})
.catch((err) => {
console.error(err)
})