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