Modules initialization in node.js and persisting their state between requests

My scenario: I am going to upload some small amount of configuration data and also rarely changing data from the database to say exports.config, that I want to use instead of config file so that app admin (not a sysadmin :) could configure the application via web interface, and I wanted to make sure that this data will not be reloaded every time this module is require'd.

Am I right to assume that whatever [initialization] code I have in node.js module (outside of functions definitions) it will be executed only once per process lifetime, regardless how many times I require this module?

Probably a stupid question, but I am struggling to understand some aspects of how node.js functions.

Yes.

The file/module can be required many times per process lifetime, but will be executed only once. At least by default.

This works out nicely for you because you can simply query your config table once at app initialization and the exported values will be constant until the app is restarted.


From the nodejs module caching docs

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.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.