-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.js
68 lines (45 loc) · 1.32 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
53
54
55
56
57
const fs = require('fs');
const { translate } = require('deepl-translator');
var path = process.argv[2];
var sourceLang = process.argv[3];
var targetLang = process.argv[4];
let data = fs.readFileSync(path);
let json = JSON.parse(data);
const delayIncrement = 100;
let delay = 0;
function iterate(o) {
Object.keys(o).forEach(async function (k) {
if (o[k] !== null && typeof o[k] === 'object') {
iterate(o[k]);
return;
}
promises.push(translateText(o, k))
delay += delayIncrement;
});
}
function translateText(o, k) {
return new Promise(resolve => setTimeout(resolve, delay)).then(() =>{
if (typeof o[k] === "string" && o[k].trim() != "") {
translate(o[k], targetLang, sourceLang)
.then(res => {
console.log(`Translation: ${res.translation}`)
o[k] = res.translation;
})
.catch(console.error);
}
else {
o[k] = o[k];
}
});
}
var promises = [];
iterate(json)
Promise.all(promises).then(() => {
setTimeout(() => {
fs.writeFile('./translated-' + targetLang + '.json', JSON.stringify(json), (err) => {
if (!err) {
console.log('done');
}
});
}, delay + 5000);
})