Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js environment variable with multiple key/values readable by node.js?

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?

like image 559
Dshiz Avatar asked Apr 29 '26 15:04

Dshiz


1 Answers

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.

like image 105
jfriend00 Avatar answered May 02 '26 09:05

jfriend00