Last active
May 4, 2023 07:35
-
-
Save dragoon/200ea5c12dff1a817b4ec9e689f39d9b to your computer and use it in GitHub Desktop.
Translate string to multiple languages with Google Translation API in Node.js (no dependecies)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const https = require('https'); | |
const API_KEY = 'XXXX'; | |
function translateText(text, targetLanguage) { | |
return new Promise((resolve, reject) => { | |
const url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}&q=${encodeURIComponent( | |
text | |
)}&target=${targetLanguage}`; | |
https.get(url, (res) => { | |
let data = ''; | |
res.on('data', (chunk) => { | |
data += chunk; | |
}); | |
res.on('end', () => { | |
const result = JSON.parse(data); | |
if (result.error) { | |
reject(result.error); | |
} else { | |
resolve(result.data.translations[0].translatedText); | |
} | |
}); | |
}).on('error', (err) => { | |
reject(err.message); | |
}); | |
}); | |
} | |
async function updateTranslationFiles(rootDir, translationId, translationText) { | |
const languageDirs = fs.readdirSync(rootDir); | |
for (const languageDir of languageDirs) { | |
const langPath = path.join(rootDir, languageDir); | |
if (fs.lstatSync(langPath).isDirectory()) { | |
const localizationFile = path.join(langPath, 'translation.json'); | |
const localizationData = JSON.parse(fs.readFileSync(localizationFile, 'utf8')); | |
if (languageDir !== 'en') { | |
localizationData[translationId] = await translateText(translationText, languageDir); | |
} else { | |
localizationData[translationId] = translationText; | |
} | |
fs.writeFileSync(localizationFile, JSON.stringify(localizationData, null, 2)); | |
} | |
} | |
} | |
(async () => { | |
const rootDir = './src/locales'; // Change this to the correct relative path | |
const translationId = process.argv[2]; | |
const translationText = process.argv[3]; | |
if (!translationId || !translationText) { | |
console.error('Please provide both translation ID and text as arguments'); | |
process.exit(1); | |
} | |
await updateTranslationFiles(rootDir, translationId, translationText); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run like this
npm run translate -- signin "Sign In"
, and if you have translation files insrc/locales/LANG/translation.json
, it will add the following to all you translation files for all languages: