greencode logo

Getting Started with Deno πŸš€

FabiΓ‘n Mendoza
Share

image

Deno is a secure runtime for JavaScript and TypeScript, introduced by the same developer behind Node.js. In 2018, this developer highlighted ten reasons for regretting aspects of Node.js, leading to the release of version 1.0.0 of Deno in 2020 as an alternative solution. One of the key concerns with Node.js was its susceptibility to security vulnerabilities, particularly those within direct and transitive dependencies. Left unpatched, these vulnerabilities pose significant risks due to the widespread use of npm packages in Node.js projects.

This article will focus on guiding readers through the installation and configuration process of Deno, enabling them to start quickly development on a more secure and reliable platform.

Installing

The official Deno website offers a quick way to install the runtime. It will show you the command line that you will need to execute according to your operating system. For example, in the case of Windows, we will use the PowerShell Invoke-RequestMethod command as follows:

irm https://deno.land/install.ps1 | iex

Copy this command, open PowerShell as administrator, paste and run it into the terminal. After a few minutes, it will finish the installation. To verify all it is ok, run this command:

deno --version

This will show you not only the Deno version but also the V8 and TypeScript versions. Deno is installed by default in the $HOME\.deno\bin directory, that you can see it with the command:

cd $HOME\.deno\bin

Commands

Now, try with the help option to see more available commands.

deno --help

As you can see, there is a list in the Commands section. We will talk about the completions command in this section and the init, info, and run as soon as we need them.

The completions command generates shell completions, which are a feature of command-line interfaces (CLI) that help users quickly and efficiently enter commands and arguments by automatically suggesting or completing them as the user types. When a user starts typing a command or argument and presses the Tab key, the shell attempts to complete the input based on the available options. Here's an example of how you can generate and use shell completions for Deno in PowerShell:

  1. Generate Shell Completions: Run the following command in your PowerShell terminal to generate the PowerShell completions for Deno:

    deno completions powershell > deno-completions.ps1

    This command will generate a PowerShell script named deno-completions.ps1 containing the Deno shell completions.

  2. Import Shell Completions: Next, you need to import the generated completions script into your PowerShell session. You can do this by running the following command:

    . .\deno-completions.ps1

    This command loads the completions script into your PowerShell session, making the Deno completions available for use.

  3. Test Shell Completions: Now that you've imported the completions script, you can test the completions by typing a partial Deno command or option and pressing the Tab key to see the available completions. For example, try typing "deno" and then press the Tab key to see a list of available commands. If you type "deno --h" and press Tab, you will see that the command is automatically completed with the help option, like this: deno --help.

Hello World

We are going to write our first project in Deno which will be a simple http server. To do this, create a folder called "hello-world" in the path you want. In our case, it will be created on drive C, so we will issue the following command:

cd c:\; mkdir hello-world; hello-world cd;

Which also places us in the work folder. Let's open the said folder in Visual Studio Code with the following command:

code

So far our project is a desert, so let's generate the minimum elements that Deno suggests. For it:

  • Open the command terminal with Ctrl+` (for English keyboard) or CTRL + Γ± (for Spanish keyboard).
  • Inside the terminal make sure you are located in the "hello-world" folder.
  • Run the init command like this:
deno init

This will generate three files. We will focus on the main.ts file, so open it and delete all its content. Next, copy the following code and paste it into that file:

import { Application } from "https://deno.land/x/oak@v14.1.1/mod.ts";

const app = new Application();
const port = 5000;

app.use((ctx) => {
  ctx.response.body = "Hello, Deno!";
});

app.addEventListener("listen", () => {
  console.log(`Listening on port ${port}`);
});

await app.listen({ port });

Note at the first row of this code in your editor, you probably will a red squiggly line, indicating there is some sort of problem. Hover over the error and you can read that an import path cannot end with a '.ts' extension. This issue happens basically because our main.ts file is written in TypeScript.

We will see how to fix this problem in the next section.

Extensions

It is no mystery that Visual Studio Code is the favourite code editor of most developers. For Deno, this is no exception. Shortly after the first version of Deno was released, also appeared an extension that helps improve the coding experience. So, press the Extensions button on the toolbar on the left side of Visual Studio Code. Type β€œDeno” in the search text box, the extension will appear as shown in the following image:

image

Press the Install button. This extension provides enhanced IntelliSense for code written in TypeScript and JavaScript, including autocomplete code suggestions, type information, and pop-up documentation. As the documentation of this extension says, you need to configure the path in which Deno was installed (the path you saw in the Installing section). One quick way to set this in Windows is creating an environment variable called DENO_INSTALL_ROOT with the value %USERPROFILE%\.deno\bin. Next, open the VS Code command palette with Ctrl+Shift+P, and run the Deno: Enable command. This will create the folder VSCode and inside it the file settings.json with the following configuration:

{
    "deno.enable": true
}

With the previous configuration, the last error disappears from our code but another one arises, but this time it is just a warning: "Uncached or missing remote URL: https://deno.land/x/oak@v14.1.1/mod.ts". This new issue makes a lot of sense, as you may have noticed we have not installed any dependencies so far, but we do not need to in an explicit way either. Deno does not require installing dependencies as Node.js does with its famous npm package manager. Instead, Deno caches the dependencies the first time we run our application, from then on it will always retrieve them from the cache. This way we will do without the "heavy" node_modules folder, another of the 10 reasons why Ryan Dalh complained about Node.js.

Thanks to the extension we have installed, we can now force caching the dependency without waiting until the first running of the code. To do this, hover again over the URL dependency and click on the Quick Fix link of the popup. This will show another popup, click on the link "Cache 'https://deno.land/x/oak@v14.1.1/mod.ts' and its dependencies". When you do this, the red wavy line disappears, which means it is now cached. To check this you can run the info command in the terminal, as follows:

deno info

The route that we need is identified as "Remote modules cache", generally something like this: C:\Users\<UserName>\AppData\Local\deno\deps\. It is there where the dependencies are cached.

Running our project

It is time to see Deno in action. For this, you have to emit the run command as follows:

deno run --allow-net main.ts

Note the option --allow-net, without this the application won't run, this is because, in Deno, security is a fundamental feature and by default, Deno operates in a restrictive security mode. When you run a program with Deno, it runs in a secure and isolated environment by default, meaning it doesn't have access to system resources like the file system or network unless explicitly allowed.

The --allow-net option is necessary for your program to access the network and make HTTP requests or other network operations. When you execute the command deno run --allow-net main.ts, you permit your program to access the network.

If you run the program without the --allow-net option, Deno will reject any attempt by your program to access the network and display an error indicating that it doesn't have permission to perform network operations.

If you navigate to the URL http://localhost:5000/, you will have the following result on screen:

image

It's important to note that Deno uses the permissions model, meaning you must explicitly grant the necessary permissions for your program to access resources like the network, file system, etc. This ensures a higher level of security and control over the operations your programs can perform.

Next steps

We quickly saw how to install Deno, and some functionalities to configure and deploy a simple and secure application. In future posts we will be able to explore more of Deno with the following topics:

  • How to build a REST API with Deno using OAK. Of course, we will delve into this dependency that we only mentioned superficially for our simple example in this post.

  • How to build a GraphQL API with Deno using Apollo Server. It is amazing all that we can make with Deno.

So stay up to date with the latest news on our Blog.πŸ‘Œ