Skip to content

Instantly share code, notes, and snippets.

@majirosstefan
Created September 10, 2021 11:17
Show Gist options
  • Save majirosstefan/85691f68ab0cd4394a8e0d5b5cae41c9 to your computer and use it in GitHub Desktop.
Save majirosstefan/85691f68ab0cd4394a8e0d5b5cae41c9 to your computer and use it in GitHub Desktop.
This is a script to translate values in JSON values which I use to localization support for apps built in my own dev studio (stefan-majiros.com)
// follow the πŸ’– for important parts
const {createWriteStream} = require('fs');
// you need to install this lib: globally or locally
var TJO = require('translate-json-object')();
// πŸ’– feel free to use any other JSON file
var json_SOURCE_OF_TRUTH = require('../src/localization/translations/en.json');
// array of iso codes
// e.g. [ 'af', 'am','az', 'be', 'bg', 'bn', 'bs', 'ca', 'co', 'cs', 'da', 'de', 'en']
var supportedLanguages = require('./supportedLanguages');
var fs = require('fs');
var path = require('path');
// πŸ’– name of the folder with translated files
const outputDirectory = 'translations';
TJO.init({
// πŸ’–
googleApiKey: '',
});
(async function main() {
try {
const outputDirectoryPath = path.join(__dirname, outputDirectory);
const translationFolderExists = fs.existsSync(outputDirectoryPath);
if (!translationFolderExists) {
fs.mkdirSync(outputDirectoryPath);
}
// πŸ’–
for (const lang of supportedLanguages) {
if (fileExists(lang) === false) {
let data = await TJO.translate(json_SOURCE_OF_TRUTH, lang);
writeToFile(data, lang);
sleep(1000);
} else {
console.log('File already exits for lang ', lang);
}
}
} catch (error) {
console.log('error ', error);
}
// πŸ’–
console.log(
'Do not forget to run prettier on translations folder to make output pretty',
);
console.log('Now you can copy translations folder into app.');
})();
function fileExists(lang) {
return fs.existsSync(pathRelative(lang));
}
function pathRelative(lang) {
return path.join(__dirname, outputDirectory, lang + '.json');
}
const writeToFile = (data, lang = 'out.txt') => {
//TODO mkdir translation folder - if it does not exist, code fails
const stream = createWriteStream(pathRelative(lang));
stream.once('open', function (fd) {
stream.write(JSON.stringify(data));
stream.end();
console.log('lang', lang, ' written');
});
};
function sleep(ms = 1000) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
@majirosstefan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment