Permalink
Browse files

initial commit

  • Loading branch information...
0 parents commit 3bb690031baac679fc7e0bcba9ed633373f87a6b @mashpie committed Mar 25, 2011
Showing with 65 additions and 0 deletions.
  1. +64 −0 i18n.js
  2. +1 −0 index.js
64 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 index.js
@@ -0,0 +1 @@
+module.exports = require('./i18n');

0 comments on commit 3bb6900

Please sign in to comment.