-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.js
52 lines (46 loc) · 1.53 KB
/
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
51
52
var translateServiceUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=";
var serviceBasePath;
var https = require('https');
function init(apiKey)
{
serviceBasePath = translateServiceUrl + apiKey;
}
function translate(from, to, key, text, filePath)
{
return new Promise(function(resolve, reject)
{
requestUrl = serviceBasePath + "&text=" + encodeURI(text) + "&lang=" + from + "-" + to;
https.get(requestUrl, (resp) =>
{
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
try
{
var translationResponse = JSON.parse(data);
var translatedText = "";
if(translationResponse.code == "200" && translationResponse.text != undefined && translationResponse.text.length > 0)
{
translatedText = translationResponse.text[0];
}
else
{
translatedText = text;
}
}
catch(e)
{
translatedText = text;
}
resolve({key: key, value: translatedText, filePath: filePath});
});
}).on("error", (err) => {
console.log(err);
reject({key: key, value: "", filePath: filePath});
});
});
}
module.exports = init;
module.exports.translate = translate;