Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mashpie committed Mar 25, 2011
0 parents commit 3bb6900
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
64 changes: 64 additions & 0 deletions i18n.js
@@ -0,0 +1,64 @@
/**
* @author Created by Marcus Spiegel on 2011-03-25. marcus@aupeo.com
* @license http://creativecommons.org/licenses/by-sa/3.0/
*/

// dependencies
var vsprintf = require('sprintf').vsprintf,
fs = require('fs'),
path = require('path'),
locales = {},
locale = 'en',
directory = './locales';

// public export
var i18n = exports;

i18n.__ = function() {
var msg = translate(arguments[0]);
if (arguments.length > 1) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));
}
return msg;
};

// ===================
// = private methods =
// ===================

// read locale file, translate a msg and write to fs if new
function translate(msg) {
if (!locales[locale]) {
read(locale);
}
if (!locales[locale][msg]) {
locales[locale][msg] = msg;
write(locale);
}
return locales[locale][msg];
}

// try reading a file
function read(locale) {
locales[locale] = {};
try {
locales[locale] = JSON.parse(fs.readFileSync(locate(locale)));
} catch(e) {
console.log('error reading locale for "'+locale+'": ' + e);
}
}

// try writing a file in a created directory
function write(locale) {
try {
stats = fs.lstatSync(directory);
} catch(e) {
fs.mkdirSync(directory, 0755);
}
fs.writeFile(locate(locale), JSON.stringify(locales[locale]));
}

// basic normalization of filepath
function locate(locale){
return path.normalize(directory + '/' + locale + '.js');
}
1 change: 1 addition & 0 deletions index.js
@@ -0,0 +1 @@
module.exports = require('./i18n');

0 comments on commit 3bb6900

Please sign in to comment.