translate.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const fs = require("fs-extra");
  2. const jsl = require("svjsl");
  3. const debug = require("./verboseLogging")
  4. const settings = require("../settings");
  5. /** Whether this module was initialized */
  6. let initialized = false;
  7. let trFile = {};
  8. /**
  9. * Initializes the translation module by caching the translations so they only need to be read from disk once
  10. * @returns {Promise}
  11. */
  12. function init()
  13. {
  14. debug("Translate", `Initializing - loading translations from "${settings.languages.translationsFile}"`);
  15. return new Promise((resolve, reject) => {
  16. fs.readFile(settings.languages.translationsFile, (err, res) => {
  17. if(err)
  18. return reject(`Error while reading translations file: ${err}`);
  19. else
  20. {
  21. trFile = JSON.parse(res.toString());
  22. debug("Translate", `Found ${Object.keys(trFile.tr).length} translations`);
  23. initialized = true;
  24. return resolve();
  25. }
  26. });
  27. });
  28. }
  29. /**
  30. * Returns the translation of a sentence of a specified language.
  31. * @param {String} lang Language code
  32. * @param {String} id The name of the translation node
  33. * @param {...any} args Arguments to replace numbered %-placeholders with. Only use objects that are strings or convertable to them with `.toString()`!
  34. * @returns {String|null} Returns `null` if no translation is available. Else returns a string
  35. */
  36. function translate(lang, id, ...args)
  37. {
  38. if(!initialized)
  39. throw new Error("translate module isnt't initialized");
  40. if(!lang)
  41. lang = settings.languages.defaultLanguage;
  42. let langTr = trFile.tr[id];
  43. if(!langTr)
  44. return null;
  45. let translation = langTr[lang.toString().toLowerCase()];
  46. if(!translation)
  47. translation = langTr[settings.languages.defaultLanguage];
  48. translation = translation.toString();
  49. if(Array.isArray(args) && translation.includes("%"))
  50. {
  51. args.forEach((arg, i) => {
  52. let rex = new RegExp(`%${i + 1}`);
  53. if(translation.match(rex))
  54. {
  55. try
  56. {
  57. translation = translation.replace(rex, arg.toString());
  58. }
  59. catch(err)
  60. {
  61. jsl.unused(err);
  62. }
  63. }
  64. });
  65. }
  66. // debug("Translate", `Translating "${id}" into ${lang} - result: ${translation}`);
  67. return translation;
  68. }
  69. /**
  70. * Returns a list of system languages (2 char code)
  71. * @returns {Array<String>}
  72. */
  73. function systemLangs()
  74. {
  75. return trFile.languages;
  76. }
  77. module.exports = translate;
  78. module.exports.init = init;
  79. module.exports.systemLangs = systemLangs;