Sub-Module Configuration Files

78 views
Skip to first unread message

Tony Barbieri

unread,
Jun 3, 2014, 9:03:42 PM6/3/14
to nod...@googlegroups.com
Hello!

I'm writing a library that will be used as a submodule and I would like to allow developers to setup configuration for it.  A few of these config options would be setting defaults for server url, login and password.  

Is there already a pattern for dealing with this situation?  I imagine it could be done a couple of ways:

  1. The submodule will always look for a config at some "hard-coded" location in the app hierarchy i.e. {app}/config/{submodule.config}?  Using this method, what is the best way for the submodule to find that location relative to the running application at run time?
  2. Provide a function as part of my exports that allows the developer to load a config from any location at run time.  Given this technique, maybe a config file is unnecessary and the config settings should just be set using javascript rather than loading a file.
Should both methods be used?  Are there other options or patterns that are common?  

Any help is much appreciated!

--
Tony

Leo Oshiro

unread,
Jun 3, 2014, 9:17:01 PM6/3/14
to nod...@googlegroups.com
Generally I pass the config to the constructor or I expose a config function.

E.g:
require('module')(config)
Or
require('module').config(config)

Thats the pattern that I have observed. I do not recommend the first.

Aria Stewart

unread,
Jun 4, 2014, 1:52:48 AM6/4/14
to nod...@googlegroups.com
I prefer the latter by far — more like a constructor. You can always do something like this:

var library = require(‘mylib’).create(require(‘./config.json’)).


signature.asc

Tony Barbieri

unread,
Jun 4, 2014, 1:54:26 PM6/4/14
to nod...@googlegroups.com
Excellent, that second option looks great.

Thanks for the help!

Best,

Tony

Mario Pareja

unread,
Jun 5, 2014, 7:52:50 PM6/5/14
to nod...@googlegroups.com

When you "require" a module, you have no control over the life time of the instance returned. You get the instance across the entire process. This is a big problem for testing. Approach two enables pushing in different configuration under different circumstances. At times, I've needed other modules to be pushed in rather than "required" directly.

Consider how you would tackle this problem if you were publishing the module as an NPM package from its own repository. You wouldn't assume that a client of the module would place a configuration file in some common place. You likely wouldn't impose a service configuration mechanism on the dev using your module.

Obviously, it depends. Sometimes simply requiring a config Json file directly is more than good enough.

Mario Pareja
Reply all
Reply to author
Forward
0 new messages