I’ve seen a few blog posts on reading in config files to node.js apps. This can be done with an eval() (which is potentially dangerous) or by reading in a file and JSON.parse()-ing it. I wanted a solution that would work on both a node app, and could also be called as JSONP in the client portion of my app, so I added a non-destructive module block to the bottom of the config file. If module.exports isn’t available, we assume we’re not running in node and call a ‘callback’ function that can be handled by like JSONP.
//config.js
conf = {
port: 8000,
name: 'app name',
otherSetting: 'etc.',
};
if( typeof module !== "undefined" && ('exports' in module)){
module.exports = function(){return conf;};
} else {
callback( conf );
}
The config file can be accessed like any other CommonJS module.
//config_test.js
var configuration = require('config.js')();
console.dir( configuration );
or included as a JSONP-like call in an HTML page like this
<html>
<head>
<script type="text/javascript">
function callback(data){
alert(data);
}
</script>
</head>
<body>
body text
<script src="config.js" type="text/javascript"></script>
</body>
</html>