Files: 23fd0e96f5d3428c5da449cebc49cd30b9b9d8be / lib / i18n.js
1953 bytesRaw
1 | var Polyglot = require('node-polyglot') |
2 | var path = require('path') |
3 | var fs = require('fs') |
4 | var asyncMemo = require('asyncmemo') |
5 | |
6 | module.exports = function (localesDir, fallback) { |
7 | return new I18n(localesDir, fallback) |
8 | } |
9 | |
10 | function I18n(dir, fallback) { |
11 | this.dir = dir |
12 | this.fallback = fallback |
13 | } |
14 | |
15 | I18n.prototype = { |
16 | constructor: I18n, |
17 | |
18 | getCatalog: asyncMemo(function (locale, cb) { |
19 | var self = this |
20 | if (!locale) return cb.call(self) |
21 | var filename = path.join(this.dir, locale.replace(/\//g, '') + '.json') |
22 | fs.access(filename, fs.R_OK, function (err) { |
23 | if (err) return cb.call(self) |
24 | fs.readFile(filename, onRead) |
25 | }) |
26 | function onRead(err, data) { |
27 | if (err) return cb.call(self, err) |
28 | var phrases |
29 | try { phrases = JSON.parse(data) } |
30 | catch(e) { return cb.call(self, e) } |
31 | var polyglot = new Polyglot({locale: locale, phrases: phrases}) |
32 | var t = polyglot.t.bind(polyglot) |
33 | t.locale = polyglot.currentLocale |
34 | cb.call(self, null, t) |
35 | } |
36 | }), |
37 | |
38 | pickCatalog: function (acceptLocales, locale, cb) { |
39 | this.getCatalog(locale, function (err, phrases) { |
40 | if (err || phrases) return cb(err, phrases) |
41 | var locales = String(acceptLocales).split(/, */).map(function (item) { |
42 | return item.split(';')[0] |
43 | }) |
44 | this.pickCatalog2(locales.concat( |
45 | process.env.LANG && process.env.LANG.replace(/[._].*/, ''), |
46 | this.fallback |
47 | ).reverse(), cb) |
48 | }) |
49 | }, |
50 | |
51 | pickCatalog2: function (locales, cb) { |
52 | if (!locales.length) return cb(null, new Error('No locale')) |
53 | this.getCatalog(locales.pop(), function (err, phrases) { |
54 | if (err || phrases) return cb(err, phrases) |
55 | this.pickCatalog2(locales, cb) |
56 | }) |
57 | }, |
58 | |
59 | listLocales: function (cb) { |
60 | fs.readdir(dir, function (err, files) { |
61 | if (err) return cb(err) |
62 | cb(null, files.map(function (filename) { |
63 | return filename.replace(/\.json$/, '') |
64 | })) |
65 | }) |
66 | } |
67 | } |
68 |
Built with git-ssb-web