Skip to main content

Creating a Web Application using Deno

Simple Web Application

So without wasting time lets jump into the code and write a simple hello world program using the abcmodule.

Create a file index.ts, and copy the code there.

import { Application } from "https://deno.land/x/abc@v1.0.0-rc10/mod.ts";

const app = new Application();

app
  .get("/hello", (c) => {
    return "Hello, Abc!";
  })
  .start({ port: 8000 });

After saving the file you can run the code using the below cmd

deno run --allow-net=0.0.0.0:8000 index.ts

Explanation: Deno is secure by default. Therefore, unless you specifically enable it, a deno module has no file, network, or environment access for example. Access to security-sensitive areas or functions requires the use of permissions to be granted to a deno process on the command line.

--allow-net=\<allow-net> Allow network access. You can specify an optional, comma-separated list of domains to provide a whitelist of allowed domains. For more information on the different kind of permissions needed in the deno you can visit Permissions in Demo

Now once you run the above cmd you can see the Hello, Abc! in the browser by redirecting to http://localhost:8000/hello

Lets Go Deeper!!!

Now let's try to serve the static file using the abc module. In the above example, app will have lots of different methods that we can use, one of them is static(), it used to serve the static files.

Let us create a folder called public in the root of the project. And inside that create an index.htmlfile. Your index.html will look something like this.

<!doctype html>
<html>
    <head>
        <title>Deno Web Application</title>
    </head>
    
    <body>
    <div>
        <h1>Deno Web Application</h1>
    </div>
    </body>
</html>

After creating this file let's modify our index.tsx file by adding the below code.

import { Application } from "https://deno.land/x/abc@v1.0.0-rc10/mod.ts";

const app = new Application();

app
  .get("/hello", (c) => {
    return "Hello World"
  })
  .static("/", "./public")
  .start({ port: 8000 });

Explanation: As you can see .static("/", "./public") we have added this route / and we are serving our static file using the static() method provided by the abc module.

static() registers a new route with path prefix to serve static files from the provided root directory.

Let's try to run this using the previous cmd that is

deno run --allow-net=0.0.0.0:8000 index.ts

Oops!! once you try to run this it will compile successfully but when you visit this pathhttp://localhost:8000/index.html, you will get below error in the browser.

{"statusCode":500,"error":"Internal Server Error","message":"read access to <CWD>, run again with the --allow-read flag"}

It's because as we know deno requires the permission to read the file from the system. Hence to run the above cmd with --allow-read flag will solve our problem. So let's use this cmd to compile our index file.

deno run --allow-read --allow-net=0.0.0.0:8000 index.ts

After successful compile, you will see the output as below.

deno-first-app

Creating a basic calculator app

Hence after the successful serving of our static file, we can also add js in it. Let start with the basic calculator app for now.

Firstly lets modify our index.html file and add the below code

<html>
  <head>
    <script src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <!-- create table -->
  <body>
    <div class="title">Deno Calculator App</div>
    <table border="1">
      <tr>
        <td colspan="3"><input type="text" id="result" /></td>
        <!-- clr() function will call clr to clear all value -->
        <td><input type="button" value="c" onclick="clr()" /></td>
      </tr>
      <tr>
        <!-- create button and assign value to each button -->
        <!-- dis("1") will call function dis to display value -->
        <td><input type="button" value="1" onclick="dis('1')" /></td>
        <td><input type="button" value="2" onclick="dis('2')" /></td>
        <td><input type="button" value="3" onclick="dis('3')" /></td>
        <td><input type="button" value="/" onclick="dis('/')" /></td>
      </tr>
      <tr>
        <td><input type="button" value="4" onclick="dis('4')" /></td>
        <td><input type="button" value="5" onclick="dis('5')" /></td>
        <td><input type="button" value="6" onclick="dis('6')" /></td>
        <td><input type="button" value="-" onclick="dis('-')" /></td>
      </tr>
      <tr>
        <td><input type="button" value="7" onclick="dis('7')" /></td>
        <td><input type="button" value="8" onclick="dis('8')" /></td>
        <td><input type="button" value="9" onclick="dis('9')" /></td>
        <td><input type="button" value="+" onclick="dis('+')" /></td>
      </tr>
      <tr>
        <td><input type="button" value="." onclick="dis('.')" /></td>
        <td><input type="button" value="0" onclick="dis('0')" /></td>
        <!-- solve function call function solve to evaluate value -->
        <td><input type="button" value="=" onclick="solve()" /></td>
        <td><input type="button" value="*" onclick="dis('*')" /></td>
      </tr>
    </table>
  </body>
</html>

As you can see the above code we have already imported our js and css inside to so lets create JS file called script.js and add the following functions in it.

//function that display value
function dis(val) {
  document.getElementById("result").value += val;
}

//function that evaluates the digit and return result
function solve() {
  let x = document.getElementById("result").value;
  let y = eval(x);
  document.getElementById("result").value = y;
}

//function that clear the display
function clr() {
  document.getElementById("result").value = "";
}

And also add some css into it by creating style.css file.

.title {
  margin-bottom: 10px;
  text-align: center;
  width: 210px;
  color: #0d8dcf;
  border: solid black 2px;
}

input[type="button"] {
  background-color: #0d8dcf;
  color: black;
  border: solid black 2px;
  width: 100%;
}

input[type="text"] {
  background-color: white;
  border: solid black 2px;
  width: 100%;
}

Great!!! Our calculator app is now almost ready, let's save all the file and reload the http://localhost:8000/index.html.

You can see our calculator app in the browser like below.


Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...