A Node.js package to translate text into multiple languages using Google Translate.
npm install googl_translate
const translate = require("googl_translate");
async function test() {
// argument as object
const result = await translate({ text: "Hello", target: "es" });
console.log(result); // Output: { detect: 'success', translated_text: 'Hola' }
// simple arguments
console.log(await translate( 'How are you',"de")); // Output: { detect: 'success', translated_text: 'Wie geht es dir' }
}
//The result will be in json format detect - tells us if the given text is in the language as given in detect it will be always success for auto
test();
const translate = require('googl_translate');
async function test() {
const result = await translate({ detect:"invalid": text: 'Hello', target: 'es' });
console.log(result); // Output: { detect: 'fail', translated_text: 'Hola' }
console.log(result.translated_text); // Output: Hola
}
//Even though detect fails but the language will still be translated into target language
test();
The translate
function takes the following parameters as an object:
translate({ detect, text, target });
-
detect (optional) — Source language code (e.g.,
"en"
for English). Defaults to"auto"
, which automatically detects the input language. - text (required) — The text you want to translate.
-
target (required) — The language code for the desired output language (e.g.,
"ar"
for Arabic).
const result = await translate({
detect: "en",
text: "hello",
target: "fr",
});
console.log(result); // Output: bonjour
- Language codes follow the ISO 639-1 standard (e.g.,
"en"
,"fr"
,"es"
,"ar"
). - Internet connection is required since it uses Google Translate API behind the scenes.