simple-dict-translator: A simple localization module for node/npm

March 3, 2018

Yes, yet another one. I bet for basically each localization problem, there’s a unique localization-solution for it.

In other words, I had a localization problem, and instead of using an off the shelf solution, I built my own. Since this was for a personal project, I don’t really see the problem, I get to spend time on things I enjoy; And I enjoy solving problems.

So my translator is supposed to be as easy as possible to use and configure. You basically only need to:

1. Fetch my translator from npm

npm install --save simple-dict-translator

Once that’s done you’ll need to is to write a little code.

2. Write a little code

var translator = require("simple-dict-translator").translator;
var translate = require("simple-dict-translator").translate;

var englishTranslations = {
    'hi':           'Hi',
    'welcome':      'Welcome'
var swedishTranslations = {
    'hi':           'Hej',
    'welcome':      'Välkommen',
    'translation':  'Översättning',
var germanTranslations = {
    'hi':           'Hallo',
    'welcome':      'Willkommen',
    'translation':  'Übersetzung',

translator.addTranslation('en_us', englishTranslations);
translator.addTranslation('sv_se', swedishTranslations);
translator.addTranslation('de_de', germanTranslations);

translator.setCurrentLocale('sv_se'); // Current language
translator.setFallbackLocale('en_us'); // Fallback language if current language is missing the translation

translate('hi'); // Hej
translate('hi', 'de_de'); // Hallo

translator.setCurrentLocale('en_us'); // Change current language to English
translator.setFallbackLocale('de_de'); // Change Fallback language to German

translate('hi'); // Hi
translate('translation'); // Übersetzung - (The English translation is missing the "translation" key, fallback is used)

That’s it, easy right?


Basically, I wanted a singleton translator that would be easy to configure and use in a project. Obviously there’s a lot better translators/localization-solutions than this. But for a small project, I didn’t want anything more complex.

As is with most of my personal projects, I’ve released the source code on github, and I’ve also published the translator on NPM.

Worth to mention is that I’ve added tests via mocha + chai for the codebase, and there’s a better looking solution for how to load multiple language files in the example folder on github.