Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to access array data in package.json

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.

like image 928
Tom Avatar asked May 01 '18 19:05

Tom


2 Answers

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.

like image 174
Mike 'Pomax' Kamermans Avatar answered Nov 07 '22 11:11

Mike 'Pomax' Kamermans


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
})
like image 28
hurricane Avatar answered Nov 07 '22 10:11

hurricane