I've got a little snippet of configuration in my package.json:
{
"name": "who-rules-app",
"config": {
"foo": "bar",
"words": [
"tpr",
"rules"
]
},
"scripts": {
"start": "node src/index.js"
}
}
From what I can tell, people generally access the config
key using process.env['npm_package_${keyname}']
, e.g.:
process.env['npm_package_config_foo']
//> "bar"
But when the value is an array, you get this ultra-hokey set of flattened, numbered keys:
process.env['npm_package_config_words_0']
//> "tpr"
process.env['npm_package_config_words_1']
//> "rules"
I could always just read the file off disk using fs
, but it's my understanding that doing things through process.env
permits this stuff to interact with environment variables, which is a pretty great way to handle configuration across different environments.
Ideally, I would like:
process.env['npm_package_config_words']
//> [ "tpr", "rules" ]
Is there a better way? A well-tested module out there? A cool pattern?
Any help is appreciated.
Instead of using what is basically a process.env hack, any recent version of Node will happily load .json files right out of the box, so simply write something like:
let package = require('./package.json');
let config = package.config || {};
let words = config.words || [];
And that's all you should need to do.
I am using dotenv package for environment variables.
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env
In your config.js
require('dotenv').config()
.env file
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
You can use them like
const db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With