Deno.js Tutorial – Complete Guide on getting started with Deno

Deno.js Tutorial – Complete Guide on getting started with Deno

We now rely on technology tools such as web pages and smartphone apps. We are only a click away from ordering food or purchasing apartments. But have you ever considered how developers create these applications? How are data stored in these applications? How are engaging user interfaces developed? It’s all because of JavaScript. We would require a JavaScript runtime environment in order to execute JavaScript outside of a browser context. Everything necessary for running JavaScript, including a JavaScript engine and APIs for interacting with the system, is included in the JavaScript runtime environment. Deno.js, the Node.js replacement, is a totally new JavaScript runtime. In this tutorial, we will go through how to get started with deno.js and how to transition from Node.js to Deno.

What is a JavaScript Runtime Environment?

Because JavaScript is interpretative, we read and analyze our code one line at a time rather than all at once. Our JavaScript code is executed by a JavaScript Engine. It, like other languages, features a call stack where functions are pushed and popped.

We require a JavaScript runtime environment in addition to a JavaScript Engine. In JavaScript, the runtime environment gives programs access to built-in libraries and objects that allow them to communicate with the outside world. We may use a vehicle engine as an example. The engine, which we utilize to power the vehicle, is the most important component of a car. However, in order to run a car engine, we need a chassis, wheels, accelerator, brake clutch, and so on. Similarly, in order for JavaScript to run, we need a JavaScript runtime environment in addition to the JavaScript Engine.

What is Deno?

Deno is a brand-new JavaScript runtime. Ryan Dahl, the creator of Node.js, developed it. It got released in 2018. Dahl had some issues with Node and intended to design a runtime that would fix those issues. Deno’s goal is to provide server-side JavaScript that is equivalent to browser JavaScript.

Deno’s most prominent qualities are as follows:

  1. Deno includes typescript support right out of the box. It means anyone can run or use TypeScript without the requirement for any extra outside or third-party libraries. While TypeScript continues to gain popularity, Deno, which includes TypeScript support out of the box, maybe a big plus for developers.
  2. Deno mainly supports the ES Module system, not the CJS Module system. It means that we may use Deno with updated import declarations.
  3. Deno is entirely safe. Unless explicitly authorized, the script cannot access system files, the network, or the environment.
  4. Deno provides a standard library with several in-built utility functions built on top of JavaScript. Furthermore, Deno has a number of built-in tools that enhance the development experience.

Deno v/s Node.js

Deno is a relatively new participant in the runtime ecosystem, whereas Node.js has been around for quite some time. Both Node.js and Deno have advantages and cons. Ryan Dahl created Deno to address some of the most severe concerns with Node.js, such as an improperly designed module system, outdated APIs, a lack of security, and so on. Apart from these, there are several advantages of utilizing Node.js over Deno, such as easy scalability, ease of learning and coding, community support, and so on.

We can view Deno can as a better alternative to Node.js; Deno may eventually replace Node.js. However, it won’t be feasible right once, mainly since a vast community depends on Node.js.

Installation and setup

Let us now install Deno on our system. Deno is available for almost all the most popular operating systems, such as Linux, Windows, and Mac.

Installing Deno on Linux

We can install Deno on Linux using the following command.

curl -fsSL https://deno.land/x/install/install.sh | sh
Code language: Bash (bash)

Installing Deno on Mac

We can install Deno on Mac using the following command.

Shell

curl -fsSL https://deno.land/x/install/install.sh | sh
Code language: Bash (bash)

Homebrew

brew install deno
Code language: Bash (bash)

Installing Deno on Windows

We can install Deno on Windows using the following command.

PowerShell

irm https://deno.land/install.ps1 | iex
Code language: PowerShell (powershell)

Chocolatey

choco install deno
Code language: PowerShell (powershell)

Scoop

scoop install deno
Code language: PowerShell (powershell)

Verifying the installation

We may validate the installation by executing the following command.

deno --version
Code language: Bash (bash)
Checking Deno version.
Checking the Deno version.

If a version gets printed on the console without any errors, it indicates that our installation is successful, and we may now use Deno on our machine.

Hello world

Writing a “Hello world” program is the initial step in learning a new programming language. Despite the fact that Deno is a JavaScript runtime rather than a programming language, it is a good idea to get started with Deno by creating a basic “Hello world.”

To begin, make a directory to hold all of the files for our Deno application. Make a new file in this directory. Within this file, we will construct a simple hello world program in JavaScript.

console.log('Hello world');
Code language: JavaScript (javascript)

To run this file, we will use the following command

deno run <filename>
Code language: Bash (bash)

We will run this command with our filename, index.js, and “Hello world” will be displayed on the console window.

deno run index.js
Code language: Bash (bash)
Hello world in Deno.
“Hello world” in Deno.

File permissions in Deno

Deno is safe by default, as we’ve already stated. Deno needs our explicit approval before using operations like making an API request, accessing the file system, etc. An executing script needs permissions given to it via runtime permission prompts or command line arguments in order to access security-sensitive functionality.

Let us use a simple script to get data from an external API as an example to learn more about file permissions in Deno.

const res = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const todo = await res.json(); console.log(todo);
Code language: JavaScript (javascript)

On trying to run the script by using the command deno run index.js, we will get an error:

Deno net access error.
Deno net access error.

Because Deno is secure by default, this error occurs. To run the scripts without problem, we must enable network requests in the event of obtaining data from a remote API. We will execute the script with the --allow-net flag to permit network requests.

deno run --allow-net index.js
Code language: Bash (bash)

The --allow-net argument allows Deno to perform API requests over the network, allowing our script to run without error and produce the required results.

Running the script with network access.
Running the script with network access.

Using Deno with TypeScript

Deno provides first-class support for both JavaScript and TypeScript. Due to this, we must include the file extension when importing files from your Deno project or third-party libraries.

We can write the same code in TypeScript to get data from an external API, and it will still operate without the requirement to install TypeScript or any other external library or package.

interface Todo { userId: string; id: number; title: string; completed: boolean; } const res: Response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const todo: Todo = await res.json(); console.log(todo);
Code language: TypeScript (typescript)
Deno with TypeScript.
Deno with TypeScript.

Using the Standard Library

Deno includes a collection of utility functions known as Deno’s standard library. Many utilities in these libraries provide functionality that we use on a daily basis, such as the FS module for interacting with the file system, the HTTP module for creating an HTTP server, and so on.

Let’s try copying a file from one directory to another using the FS module. To do so, we shall make use of the copy function supplied by Deno’s standard library’s FS module. We import the function with the ES import syntax, as well as provide the appropriate extension for the file from which we are importing the function.

import { copySync } from 'https://deno.land/[email protected]/fs/mod.ts'; copySync('./dir1/temp.txt', './dir2/temp.txt');
Code language: JavaScript (javascript)

Now, we use the following command to run the script.

deno run --allow-read --allow-write index.js
Code language: Bash (bash)

We have passed two flags here: --allow-read and --allow-write. We must give these flags for our script to access the file system and perform read and write operations.

File structure before copying.
File structure before copying.
File structure after copying.
File structure after copying.

Using the External Libraries

A Deno.js app can’t be built with only Deno’s standard library. That’s where third-party libraries (also called external libraries or just libraries) come into play. Deno.js imports libraries with absolute paths directly from the web.

Let’s utilize an external library called bcrypt, which is one of the most often used for producing password hashes. We’ll import it straight from the URL. To create a hash using the bcrypt library, write the code below.

import { hash } from 'https://deno.land/x/bcrypt/mod.ts'; const hashedString = await hash('Hi from Codedamn!'); console.log(hashedString);
Code language: JavaScript (javascript)

Now, we use the following command to run the script.

deno run --allow-net index.js
Code language: Bash (bash)

Because Async implementations utilize WebWorkers, which require network access to import Deno standard modules from within the Worker, we must pass the --allow-net flag.

Hashing a string using Bcrypt.
Hashing a string using Bcrypt.

Testing

Deno.js provides a built-in test suite for testing JavaScript or TypeScript applications. Deno.js provides us with a test function that allows us to create our test with a name/description and the actual test function. It is our responsibility to incorporate the test into the function’s body.

Let’s make a basic test. Create a file called index.test.js and use the assertEquals method to compare two values.

import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; Deno.test('Addition', () => { const a = 5; const b = 10; const sum = a + b; assertEquals(sum, 15); });
Code language: JavaScript (javascript)

We use the assertEquals function to compare two values. The first number is the desired output of our function, while the second value is the expected result. If both are correct, the test should turn green. If they do not match, the test should fail and display a red warning.

We run our test by using the following command.

deno test
Code language: Bash (bash)

The command will test all files with the naming pattern <filename>.test.<js,ts,jsx,tsx>. We can also test a single file by passing the file name as an argument.

deno test index.test.js
Code language: Bash (bash)
Testing in Deno.
Testing in Deno.

Environment Variables

Developers often utilize environment variables to store secret and sensitive information as variables within our system environment rather than in our code. We save all of the environment variables in a .env file and load these variables into our application environment when we launch the application. We may use a library like dotenv to load the environment variables into our application environment. The dotenv library is available for both Node.js and Deno.js. However, their usage differs slightly.

Let us now look at importing and using the dotenv library in our Deno.js application. Make a .env file with certain variables defined within it.

SECRET_KEY=supersecret
Code language: plaintext (plaintext)

First, we’ll import the package straight from the URL. Inside our index.js file, paste the following code.

import 'https://deno.land/x/dotenv/load.ts'; console.log(Deno.env.get('SECRET_KEY'));
Code language: JavaScript (javascript)

We have used the URL to import the file load.ts. It loads all of the environment variables onto the environment. The Deno object has access to the environment variables.

Using Environment Variables in Deno.
Using Environment Variables in Deno.

Conclusion

In this article, we learned what a JavaScript runtime environment is and why it is required. We learned what deno.js is and how it differs from the Node.js runtime. Furthermore, we installed Deno and went through its fundamentals, such as file permission, TypeScript support, standard library, etc. Finally, we looked at how to test and load environment variables in Deno.

Thank you so much for reading ?

Sharing is caring

Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.

0/20000

No comments so far