How to Build Your First Deno App: A Step-by-Step Guide
From Deno Hello World to Build an API
I've been checking out Deno and found it's a really great choice if you're looking for a JavaScript and TypeScript runtime, it comes with pre-built modules that make it super easy to develop applications without having to start everything from scratch.
Why Deno ?
Deno has a cool advantage over Node. It doesn't depend on the CommonJS module system or npm registry. Instead, it uses the ES modules system, which makes sharing and distributing modules a breeze! You can even load modules from URLs without worrying about version conflicts or package management.
By default, Deno scripts are executed in a sandboxed environment without access to sensitive resources like the file system or network. To grant access to these resources, you must explicitly provide permission using a set of flags. For instance, you can use the flag if you want your script to access the network, you can use the --allow-net
flag.
I love deno It is because it's secure and easyt also provides some cool built-in development tools to make your life easier. You'll love the code formatter (deno fmt), the linter (deno lint), the test runner (deno test), and the language server for your editor. Plus, some standard modules have been reviewed and guaranteed to work with Deno, and you can even use existing npm modules.
Read more about Permisions
I think the best way to give it a try is to build something with Deno.
Install Deno on your system.
The installation process is straightforward. As a Windows user, I only needed to run the following command in PowerShell:
irm https://deno.land/install.ps1 | iex)
If you use a different operating system, please check the official website for installation instructions.
Once the installation is complete, you can run deno --help in the terminal to see the full list of options.
C:\Users\dany.paredes>deno --help
deno 1.31.3
A modern JavaScript and TypeScript runtime
Docs: https://deno.land/manual@v1.31.3
Modules: https://deno.land/std/ https://deno.land/x/
Bugs: https://github.com/denoland/deno/issues
To start the REPL:
deno
To execute a script:
deno run https://deno.land/std/examples/welcome.ts
To evaluate code in the shell:
deno eval "console.log(30933 + 404)"
USAGE:
IDE for Deno
I will use my favorite IDE WebStorm, because it supports Deno with an extension but also, you can use VSCode or Webstorm.
A great alternative is Netzo it is more than Web IDE for Deno, it an amazing platform to build and deploy our apps. If you want to give it a try.
The Web Server Example
Before building an application, I want to create a "hello world" webserver example for Node/Deno developers. The idea is to learn how easy it is to import libraries and use built-in objects, like Response
from the fetch
API.
Create a new file, like mywebserver.ts
and paste the following code:
import { serve } from "https://deno.land/std@0.182.0/http/server.ts"
serve(() => new Response("Hello World"), { port: 8800 })
This code imports the server object from the Deno standard library, creates a server instance, and sets it up to listen on port 8800. When a request is received, the fetch API's Response object sends a "Hello World" response to the client.
As previously mentioned, to operate the web server, we must authorize it to access the network, as it relies on the library server.
When you execute the deno run mywebserver.ts command, Deno will prompt you to provide the required permissions.
deno run .\mywebserver.ts
┌ ⚠️ Deno requests net access to "0.0.0.0:8800".
├ Requested by `Deno.listen()` API
├ Run again with --allow-net to bypass this prompt.
└ Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all net permissions) >
Allow everything and our webserver by selecting option A.
Ta-da! Our web server is now returning a "Hello World" message, which could come in handy for generating a mock API.
Release notes: https://github.com/denoland/deno/releases/tag/v1.32.2
Blog post: https://deno.com/blog/v1.32
✅ Granted all net access.
Listening on http://localhost:8000/
Upgrade to New Version
While learning Deno, I stumbled upon the news of a freshly released version. Without delay, I executed a straightforward command in the terminal to make the upgrade.
deno upgrade
Looking up latest version
Found latest version 1.32.3
Downloading https://github.com/denoland/deno/releases/download/v1.32.3/deno-x86_64-pc-windows-msvc.zip
Deno is upgrading to version 1.32.3
Upgraded successfully
Release notes: https://github.com/denoland/deno/releases/tag/v1.32.3
Build A DenoPassword
I want to take a step forward, more than a simple hello-world, to develop a terminal app where the use adds the name of his resource, then generates a password for his resource.
In this scenario, we learn the following points.
Import a library `passwordGenerator`.
Take values from terminal.
Use a library and output data.
Combine multiple files.
Let's go!
First, create a new file denopass.ts
and import the passwordGenerator
library, next add two functions: createPassword
and getRandomPasswordLength
.
- The createPassword
function inputs a domain name and then generates a password.
- The getRandomPasswordLength
function produces a random number when the domain name is brief.
The final code should look something like this:
import { passwordGenerator } from "https://deno.land/x/password_generator/mod.ts";
export function createPassword(accountName: string): string {
const passwordLength = accountName.length > 8 ? accountName.length : getRandomPasswordLength();
return passwordGenerator("*", passwordLength);
}
export function getRandomPasswordLength(): number {
const min = 5;
const max = 15;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Perfect, our next step is to create the main or entry point file where we interact, show, and get values from the user.
Create a new file named main.ts
and import the createPassword
function from the denopass.ts
file.
Into the `main.ts` we will to use common used methods like console.log , console.clear and prompt.
To clear the terminal, use the command console.clear().
Use console.log('Welcome to DenoPass') to display a welcome message.
Use
prompt
to get the account name from the user.If the account name is blank, utilize Deno.exit(1) to terminate the application.
Create a password by passing the accountName to the createPassword function.
Use console.log to output the generated password to the terminal.
The final iteration of the code should appear like this:
import { createPassword } from "./denopass.ts";
console.clear();
console.log("Welcome to DenoPass");
const accountName = prompt(
"Please enter the name of the account or domain for which you want to generate a password"
);
if (!accountName) {
console.error("Account or domain name cannot be empty.");
Deno.exit(1);
}
const accountPassword = createPassword(accountName);
console.log(`The password for ${accountName} is ${accountPassword}`);
Next, from the terminal and go to the directory containing the main.ts file. After that, run the app using `deno run main.ts`:
deno run main.ts
By running the main.ts file, the app prompts the user to enter the desired name, and then generates a secure, randomized password. Once complete, the password appears in the terminal.
Yeahh! we have a password generator!
Bundle My App
In Deno, you have the ability to combine several files into one executable by utilizing the "--bundle" parameter.
For example, if you want to bundle main.ts
and denopass.ts
into a single file, you can run the following command:
PS C:\Users\dany.paredes\Desktop\code\hello_deno> deno bundle .\main.ts zuperDeno.ts
Emit "zuperDeno.ts" (6.49KB)
PS C:\Users\dany.paredes\Desktop\code\hello_deno> deno bundle .\main.ts zuperDeno.ts
A new file called zuperDeno.ts will be generated, containing the code from both main.ts and denopass.ts.
Can you imagine how exciting it would be to transform our terminal application for password generation into an API?! It would be a challenge, but I am ready for it! Let's do this!"
Turn into an API
The final task is to transform the password generator client into an API. This can be a simple process with Deno since we can utilize the built-in HTTP module to establish an HTTP server and manage incoming requests.
To begin, we'll make a new file and name it passwordApi.ts. Within this file, import the createPassword
function from denopass.ts
.
To set up an HTTP server, use the serve()
as we did a begin article, listener function that manages incoming requests and produces passwords utilizing the request parameters.
We setup the HTTP server listening on port 8800. When a GET request is received, it checks if the URL matches the pattern /password/<accountName>
and, if so, calls a function to generate a password using the <accountName>
variable. If the URL does not match the pattern, it returns a "Not Found" error.
The final code looks like:
import { createPassword } from "./denopass.ts";
import { serve } from "https://deno.land/std@0.96.0/http/server.ts";
const PORT = 8800;
const server = serve({ port: PORT });
console.log(`Listening on port ${PORT}...`);
for await (const req of server) {
const { method, url } = req;
if (method !== "GET") {
req.respond({ status: 405, body: "Method Not Allowed" });
continue;
}
const match = url.match(/^\/password\/(.+)$/);
if (match) {
const accountName = match[1];
const password = createPassword(accountName);
req.respond({ body: password });
} else {
req.respond({ status: 404, body: "Not Found" });
}
}
Run the server using the command deno run --allow-net passwordApi.ts
.
Note that you need to grant network permissions using the
--allow-net
flag because the server listens on a network port.
Once the server is up and running, navigate with the browser to http://localhost:8800/password/lebron
to generate a password for the account named lebron in the server's response.
Done! However, for enhanced user experience, consider giving Netzo a try.
Netzo: A Platform to Easily Build and Deploy Deno Apps
I've just checked out Netzo, a cloud platform that provides a comprehensive environment for creating and launching Deno applications. Thanks to Netzo, you can easily craft your own front-ends and back-ends using vanilla JavaScript/TypeScript, without having to deal with the infrastructure.
Imagine building amazing apps, APIs, and workflows using your favorite Deno frameworks, or even choose from pre-built templates offered by Netzo! And that's not all - Netzo also comes packed with easy sharing and config-less deployment features that make the development process faster and more efficient than ever before! How amazing is that?!
I am confident in developing an identical app using Netzo, as it greatly simplifies coding and releasing Deno applications.
Explore the amazing capabilities of Netzo and discover its impressive range of features by visiting https://netzo.io. You'll be amazed!
Conclusion
Great job! We've covered some Deno basics, like how to install it on your computer and how to run your first program. We've also had a chance to see how Deno stands out from Node.js and all the awesome benefits it offers.
Hey there! Deno has an awesome feature where you can easily combine external libraries into your project. We made a cool password generator client using the passwordGenerator
library to demonstrate how easy it is to turn a terminal-based app into a web-based API with Deno's help. Pretty neat, right?
So, to wrap it up, I hope this little intro on Deno has piqued your curiosity and encouraged you to dive deeper into this cool technology that prioritizes security, simplicity, and overall user experience.
- Source Code: https://github.com/danywalls/hello_deno
Image by https://twitter.com/dcdunkan