In a Node.js module, I need to run some initialization code, some code to be run only once, to parse a YAML config file on my application startup.
As a Node.js novice, I noticed that modules are loaded once, and only once (and that's very fine like that). I mean:
// ./mymodule.js
console.log('mymodule.js was run');
... displays the given message only once, even if ./mymodule.js was needed in multiple loaded modules. And that's fine.
So, for my init code, I can imagine to implement it simply like that:
// ./mymodule.js
function mymodule_init()
// Parse my config file
// ...
// Done
}
// Run my init:
mymodule_init();
console.log('mymodule.js was run');
But is it the right way to run my initialization code? Isn't there a more regular way to do it, like subscribing to
a kind of 'module_init' event, which would guarantee that my init code would be run once and only once?
Note: I found this SO link about the question : Initialize nodejs module once, use many times, but there's no really frank answer about it.