I would like to create a .env file that has a single environment variable that provides multiple key/values readable by node.js.
For instance:
USERNAME=firstname:John,lastname:Doe
Then something like:
require('dotenv').config()
let myEnvVariable = process.env.USERNAME
let firstName = myEnvVariable.firstname
let lastName = myEnvVariable.lastname
console.log(fistName, lastName)
// expected result: John Doe
Is something like this possible? If so, how do I go about it?
It might be easiest if you just put JSON as the environment variable value. Then, you can just get the value of the environment variable and do JSON.parse() on it and have a fully formed Javascript object as the result. Then, you don't have to invent your own format and don't have to write your own parsing code.
In your environment:
USERNAME={"firstname":"John","lastname":"Doe"}
Then, in your code:
const user = JSON.parse(process.env.USERNAME);
console.log(user.firstname);
console.log(user.lastname);
FYI, this is exactly the kind of things JSON was invented for - a text-only standard format for expressing data that can be generated or parsed easily from nearly any language.
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