Environment variables in Deno

0
2
Handling environment variables in Deno is well-supported, this is how you to do it.
Handling environment variables in Deno is well-supported, this is how you to do it.

Handling environment variables in Deno is well-supported, this is how you to do it.

Environment variables in Deno can be accessed through Deno.env object, which basically provides 4 methods: get(), set(), delete() and toObject().

// get a value
const Author = Deno.env.get('AUTHOR');
console.log('Author: ' + Author);

// set a value
Deno.env.set('YEAR', '2022');
console.log('Year: ' + Deno.env.get('YEAR'));

// delete value
Deno.env.delete('YEAR');
console.log('Year: ' + Deno.env.get('YEAR'));

// store all environment variables as an object
const envVars = Deno.env.toObject();
console.log(envVars);

To execute the script, it is required to provide environment variable permission --alow-env, you can do like this:

$ AUTHOR="Pete Houston" deno run --allow-env main.ts
Author: Pete Houston
Year: 2022
Year: undefined
{
  LC_CTYPE: "en_US.UTF-8",
  TERM: "xterm-256color",
  AUTHOR: "Pete Houston",
  HOMEBREW_REPOSITORY: "/opt/homebrew",
  LC_TERMINAL: "iTerm2",
  __CF_USER_TEXT_ENCODING: "0x1F5:0x0:0x0",
  HOME: "/Users/petehouston",
  SHELL: "/bin/zsh"
}

Once the environment variable is deleted, it will become undefined.

That’s all about it, have fun!