Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 3bb6900
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -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'); | |||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -0,0 +1 @@ | |||
module.exports = require('./i18n'); |