I have an array that I pull data from.
festivals = ['bonnaroo', 'lollapalooza', 'coachella']
Since I'm using heroku, it may be better to replace it with an environment variable, but I'm not sure how to do that.
Is using a JSON string as an environment variable the way to go?
short answer: yes, you can!
After creating an Array object, we can insert data. Use [] with index if you want to assign the value. array[0] = 3; array[1] = 5; array[2] = 12; array[3] = 8; array[4] = 7; You can also use the push() function to insert data.
If you have multiple environment variables in your node project, you can also create an . env file in the root directory of your project, and then use the dotenv package to load them during runtime. You can also run your js file with node -r dotenv/config index.
In this scenario, it doesn't sound like an env var is the way to go.
Usually, you'll want to use environment variables to give your application information about its environment or to customize its behavior: which database to connect to, which auth tokens to use, how many workers to fork, whether or not to cache rendered views, etc.
Your example looks more like a model, so something like a database is probably a better fit.
That said, there's no context around what your app does or how it uses festivals
, so if it does turn out that you should use an env var, then you have several options. The simplest is probably to just use a space or comma-delimited string:
heroku config:set FESTIVALS="bonnaroo lollapalooza coachella"
then:
var festivals = process.env.FESTIVALS.split(' ');
disclosure: I'm the Node.js Platform Owner at Heroku
Your example looks more of an enumeration than a config array. I'd highly recommend using a model to save it.
In case you are referring to the above array just as an example and are more curious about how can arrays be stored in an env file -
Short answer: You cannot.
Long answer: .env variables are strings So something like
BOOLEAN = true
will be treated as
BOOLEAN = "true"
and so will
FESTIVALS = ['bonnaroo', 'lollapalooza', 'coachella']
be treated as
FESTIVALS = "['bonnaroo', 'lollapalooza', 'coachella']"
Solution:
You can save the array as a delimited string in .env
FESTIVALS = "bonnaroo, lollapalooza, coachella"
In your js file you can convert it to an array using
var festivals = process.env.FESTIVALS.split(", ");
The result will be
['bonnaroo', 'lollapalooza', 'coachella']
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