For a small stateless API I'm designing, I need a very simple i18n tool. I will manage less than 30 strings in 2 languages, no more.
I decided to write a very simple i18n tool:
exports.i18nString = function (language, stringID) {
try {
var dictionary = require(`./${language}.json`)
if (Array.isArray(dictionary[stringID])) {
return dictionary[stringID][Math.floor(Math.random() * dictionary[stringID].length)];
}
return dictionary[stringID];
} catch(error) {
}
return "";
}
An example JSON dictionary:
{
"example": "This is an example",
"multi": [
"Choice 1",
"Choice 2",
"Choice 3"
]
}
It works perfectly and really fits my needs. One thing bothers me though: the presence of a require
in the function I'm calling each time in need a string.
I'm a beginner in Js, but I know that require
opens the file, reads its content and evaluates it. But I don't know if Js is smart enough to keep file's content in cache for subsequent calls. If it's the case, then my code is ok. If it's not, I might face performance issues.
Can you guys enlight me?
I found an answer while searching at random.
Here's the thing: Node.js does cache every file, as explained here:
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo')
will get exactly the same object returned, if it would resolve to the same file.
Provided require.cache
is not modified, multiple calls to require('foo')
will not cause the module code to be executed multiple times.