Any ideas?
This is what my code looks like. I followed the basic project setup guide for Node.
Init
const {Translate} = require('@google-cloud/translate').v2;
const translate = new Translate({projectId, credentials});
const text = 'The text to translate, e.g. Hello, world!';
const target = 'es';
The function to translate.
async function translateText() {
let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];
console.log('Translations:');
translations.forEach((translation, i) => {
console.log(`${text[i]} => (${target}) ${translation}`);
});
}
It's pretty frustrating that every API doc mentions that the source language gets automatically "detected", without any information about how to stop Google from guessing at it. Seems like something Google would benefit from also... Less work for them.
Found in the package's README.md
They want us to pass an "options" object that contains the from/to language codes instead of just the target (to) language code.
So we define this object
const options = {
from: 'en',
to: 'es'
};
and then our
translate.translate(text, target);
becomes
translate.translate(text, options);
it's also possible to pass a callback.
translate.translate(text, options, (err, translation) => {
if (!err) {
// translation = 'Hola'
}
});