-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle-translate.js
50 lines (44 loc) · 1.06 KB
/
google-translate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const https = require('https');
function translate(from, to, text) {
const url = `https://translate.googleapis.com/translate_a/single
?client=gtx
&ie=UTF-8
&oe=UTF-8
&dt=t
&sl=${encodeURI(from)}
&tl=${encodeURI(to)}
&q=${encodeURI(text)}`
.replace(/\s/g,'');
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const json = JSON.parse(data);
if (json[0] && json[0][0] && json[0][0][0]) {
resolve(json[0][0][0]);
} else {
reject(data);
}
} catch (err) {
reject(data);
}
});
}).on('error', (err) => {
reject(err);
});
});
}
async function test(from, to, text) {
try {
const result = await translate(from, to, text);
console.log(result);
} catch (err) {
console.log('ERROR ' + err);
}
}
test('en-US', 'da-DK', 'Hello, world!');