Files
NodeBB/src/languages.js

99 lines
2.1 KiB
JavaScript
Raw Normal View History

2014-07-09 12:21:35 -04:00
'use strict';
var fs = require('fs');
var path = require('path');
var async = require('async');
var LRU = require('lru-cache');
2016-05-16 10:32:28 -04:00
var plugins = require('./plugins');
var Languages = {};
var languagesPath = path.join(__dirname, '../public/language');
2016-05-16 10:32:28 -04:00
Languages.init = function (next) {
2016-05-16 10:32:28 -04:00
if (Languages.hasOwnProperty('_cache')) {
Languages._cache.reset();
} else {
Languages._cache = LRU(100);
}
next();
};
Languages.get = function (language, namespace, callback) {
var langNamespace = language + '/' + namespace;
2016-05-16 10:32:28 -04:00
if (Languages._cache && Languages._cache.has(langNamespace)) {
return callback(null, Languages._cache.get(langNamespace));
2016-05-16 10:32:28 -04:00
}
var languageData;
fs.readFile(path.join(languagesPath, language, namespace + '.json'), { encoding: 'utf-8' }, function (err, data) {
2016-08-16 19:46:59 +02:00
if (err && err.code !== 'ENOENT') {
return callback(err);
}
2016-05-16 10:32:28 -04:00
// If language file in core cannot be read, then no language file present
try {
languageData = JSON.parse(data) || {};
} catch (e) {
languageData = {};
}
if (plugins.customLanguages.hasOwnProperty(langNamespace)) {
Object.assign(languageData, plugins.customLanguages[langNamespace]);
2016-05-16 10:32:28 -04:00
}
2016-10-14 12:54:54 +03:00
if (Languages._cache) {
Languages._cache.set(langNamespace, languageData);
2016-10-14 12:54:54 +03:00
}
2016-05-16 10:32:28 -04:00
callback(null, languageData);
});
};
Languages.list = function (callback) {
var languages = [];
fs.readdir(languagesPath, function (err, files) {
2014-07-09 12:21:35 -04:00
if (err) {
return callback(err);
}
async.each(files, function (folder, next) {
fs.stat(path.join(languagesPath, folder), function (err, stat) {
2014-07-09 12:21:35 -04:00
if (err) {
return next(err);
}
if (!stat.isDirectory()) {
return next();
}
var configPath = path.join(languagesPath, folder, 'language.json');
fs.readFile(configPath, function (err, stream) {
2014-07-09 12:21:35 -04:00
if (err) {
2016-11-28 18:16:13 -07:00
return next(err);
}
2014-07-09 12:21:35 -04:00
languages.push(JSON.parse(stream.toString()));
next();
2014-07-09 12:21:35 -04:00
});
});
}, function (err) {
2014-07-09 12:21:35 -04:00
if (err) {
return callback(err);
}
// Sort alphabetically
languages = languages.sort(function (a, b) {
return a.code > b.code ? 1 : -1;
});
callback(err, languages);
});
});
};
2014-04-10 20:31:57 +01:00
module.exports = Languages;