Languages

Node.js - translate text from one language to another

3 points
Asked by:
Diana
720

What is the easiest way to translate some text from one language to another using Node.js?

2 answers
3 points
Answered by:
Diana
720

You can use translate package to do so.

Practical example

1. Install translate package.

npm i translate

2. Create a function that translates text passed as the first argument to the language of your choice.

const translate = require('translate');

async function translateString(text, options) {
    return await translate(text, options);
}



// Usage example 1:

const options = { from: 'eng', to: 'pl' };

translateString('Hello World!', options)
    .then(result => console.log(result))
    .catch(error => console.error(error));



// Usage example 2 (in async scope):

const options = { from: 'eng', to: 'pl' };

try {
    const result = await translateString('Hello World!', options);
    console.log(result);
} catch (error) {
    console.error(error);
}

Result:

Witaj świecie!

Note:

By default, from option is set to english, so you can simply use:

translateString('Hello World!', 'pl')

 

References

  1. translate - npm
0 comments Add comment
0 points
Answered by:
Diana
720
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join