Skip to content
DeveloperMemos

Getting Environment Variables in Deno

Deno, Environment Variables1 min read

Getting environment variables in Deno is a simple process that can be accomplished using the built-in Deno.env object. This object allows you to access the current environment variables of your system, as well as set new ones.

To get the value of an environment variable, you can use the Deno.env.get() method. This method takes the name of the environment variable you want to retrieve as its only argument. For example, to get the value of the HOME environment variable, you can use the following code:

1const home = Deno.env.get("HOME");
2console.log(home); // Outputs the value of the HOME environment variable

If the environment variable you're trying to access doesn't exist, Deno.env.get() will return undefined.

In addition to Deno.env.get(), the Deno.env object also provides a Deno.env.toObject() method, which returns an object containing all of the environment variables and their values. This can be useful if you want to access multiple environment variables at once, or if you want to iterate over all of the environment variables in your system. Here is an example of how to use Deno.env.toObject():

1const env = Deno.env.toObject();
2
3// Output all environment variables and their values
4for (const [key, value] of Object.entries(env)) {
5 console.log(`${key}: ${value}`);
6}

To set a new environment variable, you can use the Deno.env.set() method. This method takes two arguments: the name of the environment variable you want to set, and the value you want to give it. Here is an example of how to use Deno.env.set():

1Deno.env.set("FOO", "BAR");
2console.log(Deno.env.get("FOO")); // Outputs "BAR"

That's all there is to it! With the Deno.env object, you can easily access and set environment variables in your Deno applications.