Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Created February 23, 2024 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezzabuzaid/845ab0290cda35794c2ade8455e66a9e to your computer and use it in GitHub Desktop.
Save ezzabuzaid/845ab0290cda35794c2ade8455e66a9e to your computer and use it in GitHub Desktop.
DOT_NET env var style in nodejs
const env = require('dotenv').config();
const deepmerge = require('deepmerge');
const { parsed: object } = env;
let clone = {};
for(const key in object) {
if(Object.hasOwnProperty.call(object, key)) {
const value = object[key];
if(key.includes('__')) {
const keys = key.split('__');
clone = deepmerge(clone, keys.reduceRight((res, key) => ({ [key]: res }), object[key]));
delete process.env[key];
} else {
clone[key] = value;
}
}
}
for(const key in clone) {
if(Object.hasOwnProperty.call(clone, key)) {
const value = clone[key];
Object.defineProperty(process.env, key, {
get: () => value
});
}
}
console.log(process.env.ROOT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment