简体   繁体   中英

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}'] , eg:

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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM