Use dotenv in Deno


Deno is asynchronous JavaScript/TypeScript runtime. If you are not sure how and what’s of Deno, here is the links

Dotenv

dontenv is a musch familiar module for Node users, it is used to create environment variables to store secrets, Uri, port etc.

Deno have two types of module system standard and third party modules. Third party modules are from the opensource community. dontenv is one of them. You can also contribute modules to the third party library.

setup .env

Create a .env file and place the APP_PORT=3002 in the file where main.ts located.

  • import the module
  • create env constant
  • access the values through constant
import { Application }  from 'https://deno.land/x/oak@v6.0.1/mod.ts'; 
import { config } from 'https://deno.land/x/dotenv/mod.ts';
 
const env = config()
const app = new Application();
const PORT = +env.PORT || 3000 //+convert it number  
app.use( ()=>{
    console.log('Hello world');    
});
app.listen({ port:PORT });
console.log(`Server running on port ${PORT}`);

Everything in .env file is string, it is ideal for placing API, urls, dblinks et. We used + to convert the port string to number because deno port should be anumber

To run the app we need two permission one for url and other for reading .env file.

deno run --allow-net --allow-read main.ts

Now jump into the browser access your route http://127.0.0.1/.

To stop the running server use Ctrl+C

All of my Deno projects will be published on my GitHub Repo, so keep watching.

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.