What is Deno and How is it Different from Node.js?

Read it in 12 Mins

Last updated on
29th Sep, 2022
Published
01st Jan, 2022
Views
10,074
What is Deno and How is it Different from Node.js?

Deno is a JavaScript and TypeScript runtime based on the V8 JavaScript engine and the Rust programming language. It was created by Ryan Dahl, the original Node.js creator, and is geared toward productivity. Dahl made the announcement in 2018 during his talk "10 Things I Regret About Node.js."

Deno could be viewed as the successor to Node.js among all the old and new server-side runtimes/frameworks.

Architecture and inner workings:

Deno considered a variety of topics, including security, when designing the architecture. Deno put a lot of thought into creating a clean and performant way of communicating with the underlying OS without leaking details to the JavaScript side. Deno communicates with the Deno backend fromthe V8 using message-passing. The backend is the Rust component that interacts with the event loop and thus with the OS. 

Deno is made possible by four technological advances: 

  • V8 
  • TypeScript 
  • Tokio (event loop) 
  • Rust 

Core Features

List of Deno Features are: 

Out-of-the-box TypeScript support:

TypeScript extends JavaScript with optional types that make large-scale application development easier. It is a superset of JavaScript and is maintained by Microsoft. Deno's runtime is built with TypeScript in mind, and Deno's standard modules are written in TypeScript as well. It provides more control over the types of your project. In contrast to Node.js, it provides first-classTypeScript support.

Easy Installation:

Deno is simple to install because it only requires one executable file. There is no need to install any additional libraries, dependencies, or set up a development environment. It only takes a few clicks to install it and begin developing.

A More Modern and Complete Library:

Deno seeks to provide a more complete and ready-to-use environment that facilitates and accelerates development. It provides a standard set of high-quality modules that have been reviewed by the core team. It makes use of modern JavaScript and Node.js lessons to provide a seamless runtime scripting environment.

Decentralized Package Management: 

Deno does not have a package.json file or a large collection of node modules. It includes a package manager in the same executable that will fetch all resources for you. URLs are used to load modules into the application. This helps to eliminate the need for a centralised registry, such as npm for Node.js.

Security:

With Deno, a developer can grant scripts permission by using flags such as —allow-net and —allow-write. Deno provides a sandbox security layer via permissions. A programcan only access the executable's permissions as specified by the user. You're probably wondering, "How will I know which flags I need to add to execute the server?" Don't worry; a message will appear in the console log asking you to add a specific flag. 

The module system

Good news for developers! There isn't even a package.json file! Unlike Node's NPM, Deno has its own package manager. As we all know, when you install a package using npm, all required dependencies must also be installed, which adds to the complexity.  

Deno's decentralised module system performs admirably here. It includes some built-in tooling for gaining access to third-party modules. Third-party code or packages can be imported using HTTP URLs and a syntax familiar to modern JS and Angular. Packages are cached locally so that they do not need to be loaded on each run. 

However, there is a cache, so you only need to download packages and modules once. Here's an example: 

Create a file assertequals.ts and paste the following code in it. 

import { assertEquals } from "https://deno.land/std@0.100.0/testing/asserts.ts"; 
assertEquals(2 + 2, 4); 
console.log('success!') 
Run the above code using: 
deno run -A assertequals.ts 

You will see Output as: 

Deno directly imports the assertEquals symbol (which happens to be a function in the Deno standard library) from a URL in this case. It's worth noting that the URL includes version information (std@0.100.0), making it simple to support multiple versions of the same package. 

Deno has a curated list of packages available at https://deno.land but you can import packages from any URL. 

Node.js vs. Deno

Here are the key differences between Node.js and Deno. 

ES modules vs. CommonJS modules:

Deno fully supports ES modules, so we can use imports in the same way that you would in React. For example, the ES module has two significant advantages over require: the node way of importing dependencies loads resources synchronously, whereas import is synchronous, which is more performant. You can also save memory by importing only the packages you require. 

Node uses the CommonJS standard: 

const module = require(‘module-name’) 
Deno uses the standard EcmaScript modules: 
import module from ‘https://some-repo/module-name.ts' 

Note that Deno requires fully qualified module names including the extension. 

Built-in Typescript compiler vs. external support:

The typescript compiler is built into Deno by default; all you have to do is name your files with a .TSextension to use typescript in your code. Following that, you will require confirmation or installation. In Node, on the other hand, you must install a typescript update package. json, include a TS configuration file, and ensure that your modules have type support.

Decentralized Packages:

Deno eliminates the need for NPM packages and large Node modules folders. Packages are instead imported from the URL and cache to the hard drive. It means that the imported dependency is cached, and you won't have to download it again if you need to use it elsewhere.

Security:

Deno takes security seriously and prioritises it. Unlike Node, it executes the code in a sandbox, so our programdoes not have access to the file system, network, environment, variables, or the execution of other scripts by default. If we want to use these resources, we must request permissions or use the appropriate security flags when running our scripts.

Browser API:

Unlike Node, Deno has access to the browser API, which means you can use anything from the browser API without having to install any additional packages. You can, for example, use fetch right away. You must install the Node fetch package while in NodeJS. You have native access to window objectives, which lead to cleaner and fewer packaging ports.  

Installing Deno

Deno is compatible with macOS, Linux, and Windows. Deno consists of a single binary executable. 

Using Shell (macOS and Linux): 
curl -fsSL https://deno.land/x/install/install.sh | sh 
Using PowerShell (Windows): 
iwr https://deno.land/x/install/install.ps1 -useb | iex 
UsingScoop(Windows): 
scoop install deno 
UsingChocolatey(Windows): 
choco install deno 
UsingHomebrew(macOS): 
brew install deno 
UsingNix(macOS and Linux): 
nix-shell -p deno 
Build and install from source usingCargo: 
cargo install deno --locked

I use Windows so, I installed Deno on my system with PowerShell using following command: 

iwr https://deno.land/x/install/install.ps1 -useb | iex 

Use the deno command to check the version installed and use the access the REPL (Read Evaluate Print Loop) 

Your first Deno app

Create a folder with name deno-dmo and c reate a file called index.ts in the application's root folder to serve as the Deno application's starting point. To make building and routing easier, you'll use Opine, which is an Express clone for Deno. 

 

Deno differs from othersinthat there are no package managers for importing third-party libraries. You do this by entering the full URL of the library. Put that at the top of the index.ts file, and then create a simple web application. 

import { opine } from "https://deno.land/x/opine@2.0.0/mod.ts"; 
const app = opine(); 
app.get('/', (req, res) => { 
 res.send('Deno Sample'); 
}); 
app.listen(3000); 
console.log('running on port 3000'); 

To run the application, open the terminal and type: 

deno run -A index.ts 

You can see the output in the terminal as running on port 3000then go tohttp://localhost:3000you should seeDeno Sampleon a blank page. 

The -A is a development shortcut. Deno is completely locked down by default, so you'll need to pass arguments to the run command to allow access, such as —allow-net for networking and —allow-read for file system reading. The -A flag, in this case, allows everything, effectively disabling all security. 

Deno Runtime APIs

Web Platform APIs:

Deno intends to use web platform APIs (such as fetch) rather than inventing new proprietary APIs where possible. These APIs generally adhere to the specifications and should be compatible with Chrome and Firefox implementations. Because of Deno's different security model, it makes sense to deviate from the specification slightly in some cases.

Permission APIs:

When you run the deno command, the CLI grants you permissions. User code frequently assumes its own set of required permissions, but there is no guarantee that the set of granted permissions will match this during execution.

In some cases, ensuring a fault-tolerant programnecessitates a way for the program to interact with the permission system at runtime. 

Example: 

const desc1 = { name: "read", path: "/foo" } as const; 
console.log(await Deno.permissions.query(desc1)); 

When you run the above code on PowerShell, you will see output as:  

HTTP Server APIs:

Native HTTP server APIs were introduced in Deno 1.9 and later, allowing users to build robust and performant web servers in Deno. 

The API attempts to leverage as many web standards as possible while remaining simple and straightforward. 

To accept requests, you must first listen for a connection on a network port. Deno.listen() is used to accomplish this: 

const server = Deno.listen({ port: 3000}); 

If there is a problem opening the network port, Deno.listen() will throw, so in a server sense, you should wrap it in a try... catch block to handle exceptions, such as the port already being in use. 

Web Storage API:

Deno 1.10 added the Web Storage API, which allows you to store string keys and values. Persistent data functions similarly to a browser and has a storage limit of 10MB. LocalStorage persists data from execution to execution, whereas the global sessionStorage object only persists data for the current execution context.  

Workers:

Deno is compatible with the Web Worker API. 

Workers can be used to run code on multiple threads at the same time. Each Worker instance runs on a separate thread that is dedicated solely to that worker. 

Deno currently only supports module type workers; thus, when creating a new worker, the type: "module" option must be specified. 

The use of relative module specifiers in the main worker is only supported with the CLI option —location <href>. This is not a good option for portability. Instead, you can use the URL constructorand import.meta.url to quickly generate a specifier for a nearby script. Dedicated workers, on the other hand, have a location and this capability as a matter of course. 

Deploying Deno apps with Deno Deploy

Deno Deploy is an application deployer and a stripped-down runtime built on top of Deno. Deno Deploy only supports a subset of web APIs.  

Let’s create a simple application and deploy our deno application using Deno Deploy: 

Step 1: Create a folder by the name deno-deploy-demo and create a file index.js in it. 

Step 2: Add the below code in the index.js file: 

addEventListener("fetch", (event) => { 
  const response = new Response ("Hello World!", { 
    headers: {"content-type": "text/plan"}, 
  }); 
  event.respondWith(response); 
}); 

Step 3: Go tohttps://deno.com/deployand create your account.  

Step 4: Create a new project and name your project: 

Step 5: We have our project created, now add the project on your GitHub as a repository. For this article, I am considering that you have a GitHub account. 

Step 6: Now, go to the settings option and select Git. 

Step 7: Under the Git Integration part, select the repository you have created for the project on your GitHub account.  

Step 8: Now, go down in the File part and click on the small arrow to deploy your project. You will see a page like this:  

Step 9: Click on any of the link in the Domain Part to access your Deployed Application.  

Should you be usingDenoinstead of Node.js?  

Deno's goal is to be an alternative to Node, not a replacement for it. I'd say that the vast majority of developers are satisfied with the way Node.js is evolving and aren't looking to change things up. 

Deno's emphasis on security, as well as the ability to bundle the entire codebase into a single file., It presents an excellent opportunity for Deno to become the go-to tool for JavaScript developers when it comes to creating utility scripts that would otherwise be written in languages such as Bash or Python. 

Those who are already using TypeScript or coming from other languages may find the transition easier, but Node.js developers will have no trouble switching from Deno to Node.js and back again. 

Deno, on the other hand, has an exciting advantage: 

  • Its module system is identical to client-side JavaScript. 
  • It implements many browser APIs, such as referencing a window object, setting event listeners, launching Web Workers, making remote server requests with the Fetch() API, and more. 

But is it time to ditch Node? 

Deno is a new project with a lot of potentials. It is based on Node.js's experience and hard lessons. It has many technical advantages over Node.js. It is built with a cutting-edge technology stack. The big question is whether it will replace JavaScript and Typescript as the primary backend runtime. I believe it is too early to tell, but it will be very interesting to see what happens. 

Profile

Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

Develop the skills of the future via outcome-based immersive learning

Speak to our Career Advisor now!

Select
Your Message (Optional)