Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
The i18n npm package is a lightweight internationalization library for Node.js applications. It provides a simple way to manage translations and localization for your application, supporting multiple languages and locales.
Basic Setup
This code demonstrates how to set up the i18n package in a Node.js application. It configures the locales and the directory where translation files are stored, and initializes i18n middleware for use in an Express app.
const i18n = require('i18n');
// Configure i18n
i18n.configure({
locales: ['en', 'es'],
directory: __dirname + '/locales'
});
// Initialize i18n
app.use(i18n.init);
Translation
This feature allows you to translate strings based on the current locale. You can also include variables in the translation strings.
i18n.__('Hello'); // Returns 'Hello' in the current locale
// With variables
i18n.__('Hello %s', 'John'); // Returns 'Hello John' in the current locale
Changing Locale
This code demonstrates how to change the current locale dynamically. After setting the locale to 'es' (Spanish), the translation for 'Hello' will be returned in Spanish.
i18n.setLocale('es');
i18n.__('Hello'); // Returns 'Hola' if the Spanish translation is available
Using in Templates
This feature shows how to use i18n translations within template engines like EJS. The translated string is passed to the template as a variable.
app.get('/', function(req, res) {
res.render('index', { title: res.__('Hello') });
});
i18next is a powerful internationalization framework for JavaScript, including both client-side and server-side support. It offers more advanced features compared to i18n, such as nested translations, pluralization, and context-based translations.
Polyglot.js is a small i18n helper library that provides a simple way to manage translations. It is less feature-rich than i18n but is very lightweight and easy to integrate into small projects.
Node-Polyglot is a Node.js version of Polyglot.js, offering similar functionality for server-side applications. It is a good alternative for projects that require a minimalistic approach to internationalization.
Lightweight simple translation module with dynamic json storage. Uses common __('...') syntax in app and templates. Stores language files in json files compatible to webtranslateit json format. Adds new strings on-the-fly when first used in your app. No extra parsing needed.
npm install i18n
npm test
// load modules
var express = require('express'),
i18n = require("i18n");
now you are ready to use a global i18n.__('Hello')
. Global assumes you share a common state of localization in any time and any part of your app. This is usually fine in cli-style scripts. When serving responses to http requests you'll need to make sure that scope is NOT shared globally but attached to your request object.
Minimal example, just setup two locales
i18n.configure({
locales:['en', 'de']
});
i18n.configure({
// setup some locales - other locales default to en silently
locales:['en', 'de'],
// you may alter a site wide default locale
defaultLocale: 'de',
// sets a custom cookie name to parse locale settings from - defaults to NULL
cookie: 'yourcookiename',
// where to store json files - defaults to './locales'
directory: './mylocales',
// whether to write new locale information to disk - defaults to true
updateFiles: false,
// setting extension of json files - defaults to '.json' (you might want to set this to '.js' according to webtranslateit)
extension: '.js',
});
In your app, when not registered to a specific object:
var greeting = i18n.__('Hello');
In an express app, you might use i18n.init to gather language settings of your visitors and also bind your helpers to response object honoring request objects locale, ie:
// Configuration
app.configure(function() {
[...]
// default: using 'accept-language' header to guess language settings
app.use(i18n.init);
[...]
});
in your apps methods:
app.get('/de', function(req, res){
var greeting = res.__('Hello');
});
in your templates (depending on your template engine)
<%= __('Hello') %>
${__('Hello')}
In general i18n has to be attached to the response object to let it's public api get accessible in your templates and methods. As of 0.4.0 i18n tries to do so internally via i18n.init
, as if you were doing it in app.configure
on your own:
app.use(function(req, res, next) {
// express helper for natively supported engines
res.locals.__ = res.__ = function() {
return i18n.__.apply(req, arguments);
};
[...]
next();
});
Different engines need different implementations, so yours might miss or not work with the current default helpers. This one showing an example for mustache in express:
// register helper as a locals function wrapped as mustache expects
app.use(function (req, res, next) {
// mustache helper
res.locals.__ = function () {
return function (text, render) {
return i18n.__.apply(req, arguments);
};
};
[...]
next();
});
You could still setup your own implementation. Please refer to Examples below, post an issue or contribute your setup.
As inspired by gettext there is currently support for sprintf-style expressions. Named parameters are on roadmap.
var greeting = __('Hello %s, how are you today?', 'Marcus');
this puts Hello Marcus, how are you today?. You might add endless arguments and even nest it.
var greeting = __('Hello %s, how are you today? How was your %s.', 'Marcus', __('weekend'));
which puts Hello Marcus, how are you today? How was your weekend.
you might even use dynamic variables as they get interpreted on the fly. Better make sure no user input finds it's way to that point as they all get added to the en.js
file if not yet existing.
var greetings = ['Hi', 'Hello', 'Howdy'];
for (var i=0; i < greetings.length; i++) {
console.log( __(greetings[i]) );
};
which puts
Hi
Hello
Howdy
different plural froms are supported as response to count
:
var singular = __n('%s cat', '%s cats', 1);
var plural = __n('%s cat', '%s cats', 3);
this puts 1 cat or 3 cats and again these could get nested:
var singular = __n('There is one monkey in the %%s', 'There are %d monkeys in the %%s', 1, 'tree');
var plural = __n('There is one monkey in the %%s', 'There are %d monkeys in the %%s', 3, 'tree');
putting There is one monkey in the tree or There are 3 monkeys in the tree
Will get modular support for different storage engines, currently just json files are stored in filesystem.
the above will automatically generate a en.json
by default inside ./locales/
which looks like
{
"Hello": "Hello",
"Hello %s, how are you today?": "Hello %s, how are you today?",
"weekend": "weekend",
"Hello %s, how are you today? How was your %s.": "Hello %s, how are you today? How was your %s.",
"Hi": "Hi",
"Howdy": "Howdy",
"%s cat": {
"one": "%s cat",
"other": "%s cats"
},
"There is one monkey in the %%s": {
"one": "There is one monkey in the %%s",
"other": "There are %d monkeys in the %%s"
},
"tree": "tree"
}
that file can be edited or just uploaded to webtranslateit for any kind of collaborative translation workflow:
{
"Hello": "Hallo",
"Hello %s, how are you today?": "Hallo %s, wie geht es dir heute?",
"weekend": "Wochenende",
"Hello %s, how are you today? How was your %s.": "Hallo %s, wie geht es dir heute? Wie war dein %s.",
"Hi": "Hi",
"Howdy": "Hallöchen",
"%s cat": {
"one": "%s Katze",
"other": "%s Katzen"
},
"There is one monkey in the %%s": {
"one": "Im %%s sitzt ein Affe",
"other": "Im Baum sitzen %d Affen"
},
"tree": "Baum"
}
Logging any kind of output is moved to debug module. To let i18n output anything run your app with DEBUG
env set like so:
$ DEBUG=i18n:* node app.js
i18n exposes three log-levels:
if you only want to get errors and warnings reported start your node server like so:
$ DEBUG=i18n:warn,i18n:error node app.js
Combine those settings with you existing application if any of you other modules or libs also uses debug
i18n.getCatalog
this.locale
to __
and __n
Copyright (c) 2011-2013 Marcus Spiegel marcus.spiegel@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
lightweight translation module with dynamic json storage
The npm package i18n receives a total of 120,270 weekly downloads. As such, i18n popularity was classified as popular.
We found that i18n demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.