Created
September 25, 2023 09:48
-
-
Save elshanx/4066ff70bea00359dc4f10da5d9e2a94 to your computer and use it in GitHub Desktop.
Nodejs script for updating Angular i18n json files in CLI
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
// Usage example: | |
// node updateTranslations.js COMMON are_you_sure "Are you sure?" az,en,ru | |
// or | |
// node updateTranslations.js COMMON are_you_sure "Are you sure?" // this will update all three languages. it's the same as above | |
const fs = require("fs"); | |
const path = require("path"); | |
// Get command-line arguments | |
const args = process.argv.slice(2); | |
// Check if there are enough arguments | |
if (args.length < 3) { | |
console.error('\x1b[31mError:\x1b[0m Usage: node updateTranslations.js <category> <key> <value> languages'); | |
process.exit(1); | |
} | |
// Extract arguments | |
const category = args[0]; | |
const key = args[1]; | |
const value = args[2]; | |
const languages = args[3] ? args[3].split(",") : ["az", "en", "ru"]; | |
// Define the directory where your translation files are located | |
const translationDir = path.join(__dirname, "src", "assets", "i18n"); | |
// Loop through each language file and update the translations | |
languages.forEach((language) => { | |
const filePath = path.join(translationDir, `${language}.json`); | |
// Read the existing JSON file | |
let existingTranslations = {}; | |
try { | |
existingTranslations = JSON.parse(fs.readFileSync(filePath, "utf8")); | |
} catch (error) { | |
console.error(`\x1b[31mError:\x1b[0m Error reading ${filePath}:`, error); | |
return; | |
} | |
// Add the new translation key and value to the specified category | |
existingTranslations[category][key] = value; | |
// Write the updated JSON back to the file | |
try { | |
fs.writeFileSync(filePath, JSON.stringify(existingTranslations, null, 2)); | |
console.log(`\x1b[32mSuccess:\x1b[0m Updated translations for ${language}`); | |
} catch (error) { | |
console.error(`\x1b[31mError:\x1b[0m Error writing ${filePath}:`, error); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment