Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. var fs = require('fs')
  2. var path = require('path')
  3. var util = require('util')
  4. function Y18N (opts) {
  5. // configurable options.
  6. opts = opts || {}
  7. this.directory = opts.directory || './locales'
  8. this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true
  9. this.locale = opts.locale || 'en'
  10. this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true
  11. // internal stuff.
  12. this.cache = {}
  13. this.writeQueue = []
  14. }
  15. Y18N.prototype.__ = function () {
  16. if (typeof arguments[0] !== 'string') {
  17. return this._taggedLiteral.apply(this, arguments)
  18. }
  19. var args = Array.prototype.slice.call(arguments)
  20. var str = args.shift()
  21. var cb = function () {} // start with noop.
  22. if (typeof args[args.length - 1] === 'function') cb = args.pop()
  23. cb = cb || function () {} // noop.
  24. if (!this.cache[this.locale]) this._readLocaleFile()
  25. // we've observed a new string, update the language file.
  26. if (!this.cache[this.locale][str] && this.updateFiles) {
  27. this.cache[this.locale][str] = str
  28. // include the current directory and locale,
  29. // since these values could change before the
  30. // write is performed.
  31. this._enqueueWrite([this.directory, this.locale, cb])
  32. } else {
  33. cb()
  34. }
  35. return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args))
  36. }
  37. Y18N.prototype._taggedLiteral = function (parts) {
  38. var args = arguments
  39. var str = ''
  40. parts.forEach(function (part, i) {
  41. var arg = args[i + 1]
  42. str += part
  43. if (typeof arg !== 'undefined') {
  44. str += '%s'
  45. }
  46. })
  47. return this.__.apply(null, [str].concat([].slice.call(arguments, 1)))
  48. }
  49. Y18N.prototype._enqueueWrite = function (work) {
  50. this.writeQueue.push(work)
  51. if (this.writeQueue.length === 1) this._processWriteQueue()
  52. }
  53. Y18N.prototype._processWriteQueue = function () {
  54. var _this = this
  55. var work = this.writeQueue[0]
  56. // destructure the enqueued work.
  57. var directory = work[0]
  58. var locale = work[1]
  59. var cb = work[2]
  60. var languageFile = this._resolveLocaleFile(directory, locale)
  61. var serializedLocale = JSON.stringify(this.cache[locale], null, 2)
  62. fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
  63. _this.writeQueue.shift()
  64. if (_this.writeQueue.length > 0) _this._processWriteQueue()
  65. cb(err)
  66. })
  67. }
  68. Y18N.prototype._readLocaleFile = function () {
  69. var localeLookup = {}
  70. var languageFile = this._resolveLocaleFile(this.directory, this.locale)
  71. try {
  72. localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8'))
  73. } catch (err) {
  74. if (err instanceof SyntaxError) {
  75. err.message = 'syntax error in ' + languageFile
  76. }
  77. if (err.code === 'ENOENT') localeLookup = {}
  78. else throw err
  79. }
  80. this.cache[this.locale] = localeLookup
  81. }
  82. Y18N.prototype._resolveLocaleFile = function (directory, locale) {
  83. var file = path.resolve(directory, './', locale + '.json')
  84. if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
  85. // attempt fallback to language only
  86. var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json')
  87. if (this._fileExistsSync(languageFile)) file = languageFile
  88. }
  89. return file
  90. }
  91. // this only exists because fs.existsSync() "will be deprecated"
  92. // see https://nodejs.org/api/fs.html#fs_fs_existssync_path
  93. Y18N.prototype._fileExistsSync = function (file) {
  94. try {
  95. return fs.statSync(file).isFile()
  96. } catch (err) {
  97. return false
  98. }
  99. }
  100. Y18N.prototype.__n = function () {
  101. var args = Array.prototype.slice.call(arguments)
  102. var singular = args.shift()
  103. var plural = args.shift()
  104. var quantity = args.shift()
  105. var cb = function () {} // start with noop.
  106. if (typeof args[args.length - 1] === 'function') cb = args.pop()
  107. if (!this.cache[this.locale]) this._readLocaleFile()
  108. var str = quantity === 1 ? singular : plural
  109. if (this.cache[this.locale][singular]) {
  110. str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other']
  111. }
  112. // we've observed a new string, update the language file.
  113. if (!this.cache[this.locale][singular] && this.updateFiles) {
  114. this.cache[this.locale][singular] = {
  115. one: singular,
  116. other: plural
  117. }
  118. // include the current directory and locale,
  119. // since these values could change before the
  120. // write is performed.
  121. this._enqueueWrite([this.directory, this.locale, cb])
  122. } else {
  123. cb()
  124. }
  125. // if a %d placeholder is provided, add quantity
  126. // to the arguments expanded by util.format.
  127. var values = [str]
  128. if (~str.indexOf('%d')) values.push(quantity)
  129. return util.format.apply(util, values.concat(args))
  130. }
  131. Y18N.prototype.setLocale = function (locale) {
  132. this.locale = locale
  133. }
  134. Y18N.prototype.getLocale = function () {
  135. return this.locale
  136. }
  137. Y18N.prototype.updateLocale = function (obj) {
  138. if (!this.cache[this.locale]) this._readLocaleFile()
  139. for (var key in obj) {
  140. this.cache[this.locale][key] = obj[key]
  141. }
  142. }
  143. module.exports = function (opts) {
  144. var y18n = new Y18N(opts)
  145. // bind all functions to y18n, so that
  146. // they can be used in isolation.
  147. for (var key in y18n) {
  148. if (typeof y18n[key] === 'function') {
  149. y18n[key] = y18n[key].bind(y18n)
  150. }
  151. }
  152. return y18n
  153. }