I have a util/config.json
file like below:
{
"dev": {
"db": {
"host": "localhost",
"user": "root",
"pass":"*****"
},
"json_indentation": 4,
"database": "my-app-db-dev"
}
"prod":{
"db": {
"host": "somethingt",
"user": "root",
"pass":"****"
},
"json_indentation": 4,
"database": "my-app-db-dev"
}
}
from a util/config.js
file, I have exported it to my app.js
const config = require('./config.json')
const environment = process.env.NODE_ENV || 'dev'
const defaultConfig = config.environment;
console.log(defaultConfig) // shows undefined why?
module.exports = defaultConfig
app.js
is like so:
const express = require('express')
const config = require('./util/config')
but it my defaultConfig shows undefined and can't fetch the data for dev
( npm run dev in app.js directory ) while I have set the NODE_ENV variable like this in my package.json:
"scripts": {
"dev": "set NODE_ENV=dev && nodemon app.js",
"prod": "set NODE_ENV=prod && nodemon app.js"
}
You can try following snippet
const config = require('./config.json')
const environment = process.env.NODE_ENV || 'dev'
const defaultConfig = config[environment];
console.log(defaultConfig) // shows undefined why?
module.exports = defaultConfig
const defaultConfig = config.environment;
searches an 'environment'
string key in the config
.
Try const defaultConfig = config[environment];
to search for the value of the environment
variable.
See Property accessors on MDN.
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.