Simple localization middleware for Express (and the like).
var app = require('express')();
var mlang = require('mlang');
app.use(mlang({
languages: ['en', 'de', 'it', 'fr'],
path: './locale',
cookie: 'lang'
}));
app.get('/', function(req, res){
res.send(res.locals._('message.hello');
});
The mlang
function call accepts an object with several configuration options.
Path to the language files.
- default
''
All available languages.
- default
[]
- when
autoDetect
is allowed,mlang
will attempt to match the langugaes in the order they are entered.
Default language.
- default
'en'
- language to use when no other match was found
Detect language automatically from headers.
- default
true
Cookie name to read language from.
- default
false
- uses
express-cookie
if present, otherwise attempts to parse directly from headers - has higher priority than
autoDetect
- empty or
false
if cookies shouldn't be used
"Namespace" to use when appending to res.locals
.
- default
''
- will append to
res.locals.ns
instead of directlyres.locals
Every language file is a basic Node.js module that exports an object. The file name must be the same as the language code.
module.exports = {
message: {
hello: 'Hello World',
welcome: 'Welcome %s, dear %s'
}
};
mlang
uses plain objects, allowing you to access all localized text directly using normal object notation.
In addition to that, mlang
adds a special _
function on each object.
h1= message.hello
h1= _('message.hello')
The added benefit of using _
function is that you can pass additional arguments in sprintf
style that will be replaced into the string.
// message.welcome = "Welcome %s, dear %s"
h1= _('message.welcome', 'to my site', 'John') // will output "Welcome to my site, dear John"
mlang
also appends the language code to _lang
property if it doesn't exist already. This can be used inside HTML lang
attributes, for example.
I wanted a simple localization package for my new Node.js project, and while there are already very powerful packages for this, they felt way too much for my simpler, more basic, needs (I'm aware there are even simpler ones) and so I decided to try it out and built my own.