-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathtranslateFile.js
61 lines (52 loc) · 1.53 KB
/
translateFile.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
58
59
60
61
// Translate a file using google translate
const fs = require('fs')
const request = require('request')
const fileName = process.argv[2]
const googleApiToken = process.argv[3]
console.info(`Translating file: ${fileName}`)
const json = fs.readFileSync(`../locales/base/${fileName}`)
const strings = JSON.parse(json)
console.info(`Found ${Object.keys(strings).length} strings`)
function translateString(s) {
return new Promise((resolve, reject) => {
console.info(`Looking up ${s}`)
request.post(
'https://translation.googleapis.com/language/translate/v2',
{
headers: {
Authorization: `Bearer ${googleApiToken}`,
},
json: {
format: 'text',
q: s,
source: 'en',
target: 'es',
},
},
(error, res, body) => {
if (error) {
reject(error)
return
}
resolve(body.data.translations[0].translatedText)
}
)
})
}
async function translateStrings(stringsToTranslate) {
const translations = {}
const promises = Promise.all(
Object.keys(stringsToTranslate).map(async (key) => {
const val = stringsToTranslate[key]
if (typeof val === 'string') {
const t = await translateString(val)
translations[key] = t
} else if (typeof stringsToTranslate === 'object') {
translations[key] = await translateStrings(val)
}
})
)
await promises
return translations
}
translateStrings(strings).then((translations) => console.log(JSON.stringify(translations)))