4

I always receive the following error when calling i18n.__n('..'):

TypeError: Cannot read property 'toLowerCase' of undefined
at Object.i18nTranslatePlural [as __n] (/home/runner/node_modules/i18n/i18n.js:367:31)
at evalmachine.<anonymous>:14:18
at Script.runInContext (vm.js:74:29)
at Object.runInContext (vm.js:182:6)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:180:13)
at addChunk (_stream_readable.js:274:12)
at readableAddChunk (_stream_readable.js:261:11)
at ReadStream.Readable.push (_stream_readable.js:218:10)

By the way, i18n.__('..') works like a charm!

Here is the code:

index.js

var i18n = require("i18n");
var path = require('path');

var __dirname = path.resolve();

i18n.configure({
    locales:['en', 'de'],
    directory: __dirname + '/locales',
    defaultLocale: 'de',
});

console.log(i18n.__('test'));

console.log(i18n.__n('%s horse', 3)); 

locales/de.json

{
  "test": "Das ist ein Test",
  "%s horse" : {
    "one": "%s Pferd",
    "other": "%s Pferde"
  }
}

locales/en.json

{
  "test": "This is a test",
  "%s horse" : {
    "one": "%s horse",
    "other": "%s horses"
  }
}

Hope some can give me an advice what I did wrong or how I can fix the problem. I ran the code on my mac book and on https://repl.it/languages/nodejs. Same result.

mihai
  • 37,072
  • 9
  • 60
  • 86

1 Answers1

3

It seems the library is in trouble finding a proper locale when calling __n. Simply set i18n.setLocale('de') and it works. The code as shown below will output

Das ist ein Test
1 Pferd
3 Pferde

I was expecting that the defaultLocale would suffice but it seems not. Hope this answer helps!

var i18n = require("i18n");
var path = require('path');

var __dirname = path.resolve();

i18n.configure({
    locales:['en', 'de'],
    directory: __dirname + '/locales',
    defaultLocale: 'de'

});

i18n.setLocale('de')
console.log(i18n.__('test'));
console.log(i18n.__n("%s horse", 1));
console.log(i18n.__n("%s horse", 3));

Just for your information, I debugged it by registering some debug functions like this in the configure() call

logDebugFn: console.log,
logWarnFn: console.log,
logErrorFn: console.log

Then, without the setLocale() call I got this WARN: No locale found - check the context of the call to __(). Using de as current locale. Forcing a current locale on the i18n object solved this issue.

tgo
  • 1,515
  • 7
  • 11