EN
Node.js - translate text from one language to another
2 answers
3 points
What is the easiest way to translate some text from one language to another using Node.js?
2 answers
3 points
You can use translate package to do so.
Practical example
1. Install translate package.
xxxxxxxxxx
1
npm i translate
2. Create a function that translates text passed as the first argument to the language of your choice.
xxxxxxxxxx
1
const translate = require('translate');
2
3
async function translateString(text, options) {
4
return await translate(text, options);
5
}
6
7
8
9
// Usage example 1:
10
11
const options = { from: 'eng', to: 'pl' };
12
13
translateString('Hello World!', options)
14
.then(result => console.log(result))
15
.catch(error => console.error(error));
16
17
18
19
// Usage example 2 (in async scope):
20
21
const options = { from: 'eng', to: 'pl' };
22
23
try {
24
const result = await translateString('Hello World!', options);
25
console.log(result);
26
} catch (error) {
27
console.error(error);
28
}
Result:
xxxxxxxxxx
1
Witaj świecie!
Note:
By default,
from
option is set to english, so you can simply use:xxxxxxxxxx
1translateString('Hello World!', 'pl')
References
0 commentsShow commentsAdd comment
0 points
0 commentsAdd comment