• Read The Deno Handbook in freeCodeCamp
  • By Flavio Copes
  • Published on 2020-05-12
  • Translator: Hylerrix, Yunkou
  • Proofreader: Hylerrix
  • Note: This article follows the freeCodeCamp translation specification and will be included in the translation of Deno’s Study.
  • Note: freeCodeCamp.org, a non-profit organization founded in 2014 with the mission of “helping people learn to code for free”, has created a large number of free programming tutorials, including interactive courses, video courses, articles, and more. The offline developer community spans over 160 countries and 2,000 cities. We are helping millions of people around the world learn to code. We want to give everyone in the world access to free, quality programming education resources to become a developer or use programming to solve problems. Search and follow the wechat official account “freeCodeCamp” for more information.

I explore new projects every week, and it’s rare to find a project like Deno that fascinates me so much.

In this manual I want to give you a quick start on Deno. I’ll compare it to Node.js and help you build your first REST API Demo on Deno.

directory

  1. What is Deno?
  2. Why Deno? Why now?
  3. Should you learn Deno?
  4. Will Deno replace Node.js?
  5. First-class TypeScript support
  6. Similarities and differences with Node.js
  7. No more package manager
  8. Install Deno
  9. Deno command
  10. Your first Deno app
  11. Deno code instance
  12. Your first Deno App (Deep Edition)
  13. Deno Safety Sandbox
  14. Formatting code
  15. The standard library
  16. Another Deno example
  17. Does Deno have Express/Hapi/Koa/*?
  18. Example: Building the REST API with Oak
  19. More content
  20. trivia
  21. conclusion

In addition, you can get the PDF/ePub/Mobi version of the Deno manual here.

What is Deno?

If you’re familiar with the popular server-side JavaScript runtime Node.js, Deno is just like Node.js, but a new JavaScript/TypeScript runtime that is profoundly improved in many ways.

Let’s take a quick look at Deno’s feature list:

  • Deno is based on the latest JavaScript language;
  • Deno has a wide range of standard libraries;
  • With TypeScript at its core, Deno offers many advantages in many unique ways, including first-class TypeScript support (Deno automatically compiles TypeScript without you having to compile it alone);
  • Deno embraces ES module standards;
  • Deno has no package manager;
  • Deno has a first-classawaitSyntax support;
  • Deno built-in test tool;
  • Deno is designed to be as compatible with browsers as possible, for example by providing built-in objectsfetchAnd globalwindowObject.

We will explore all of these features in this manual.

Node.js may look a little dated after you’ve practiced Deno and learned about its unique features.

In particular, because the Node.js API is based on the callback mechanism, because Node.js was written before Promise and Async/Await definitions were standard. You can’t make a completely new change to this mechanism in Node.js, because such a change would have a “devastating” effect. Therefore, in Node.js we get stuck calling back a lot of apis.

Node.js is awesome and will continue to be the de facto standard in the JavaScript world for the foreseeable future. But I think we’ll see Deno increasingly recognized and adopted for its first-class TypeScript support and its built-in, extensive modern standard library.

With no history of backward compatibility, Deno will be able to take on all engineering projects written using modern Web technologies. But the reality is that there’s no guarantee that something like Node.js won’t happen to Deno in 10 years, and that a new technology won’t replace Deno.

Why Deno? Why now?

About 2 years ago, Node.js creator Ryan Dahl first introduced Deno at JSConf EU. It would be very interesting to watch the video of the speech. If you have a lot of exposure to Node.js and JavaScript on a regular basis, don’t miss this video.

Each project manager must issue a decision. Ryan still regrets looking back at some of node.js’s early designs. Moreover, thanks to ongoing standards such as ES6/2016/2017, JavaScript today is very different from what it was when Node.js was founded in 2009.

So he started a new project to create a second-generation JavaScript runtime on the server side.

Nascent technologies take a lot of time to mature, which is why I’m writing this manual now, rather than two years ago. Now, the first official, stable version of Deno V1.0 is just around the corner (May 13, 2020, if not unexpected).

Translator’s Note: This manual was translated when Deno 1.0 was released.

1.0 May seem like just a number, but in terms of community engagement, it means there won’t be too many major disruptive changes to Deno until Deno 2.0 — which is important because you can finally learn from the current stable version of Deno.

Should you learn Deno?

It’s not that easy to answer.

Learning something as new as Deno requires a lot of upfront technology. Here’s my advice: If you’re new to server-side JavaScript programming, and you don’t know Anything about Node.js, and you don’t have any experience developing TypeScript applications — start with Node.js.

After all, in popular opinion, no one would be fired for choosing to study Node.js these days.

But if you like TypeScript, don’t want to rely on huge NPM packages in your projects, and want to use await syntax everywhere, then you probably need Deno.

Will Deno replace Node.js?

Can’t. The Node.js ecosystem is already huge and well-developed, supported by tens of thousands of great technologies, and will continue to thrive for decades to come.

First-class TypeScript support

Deno is based on Rust and TypeScript, two rapidly growing languages today.

This means that even though we may choose to write pure JavaScript code to run on Deno written in the TypeScript language, we can still reap many of TypeScript’s benefits.

Running TypeScript code with Deno doesn’t require any manual compilation — Deno does this step for you automatically.

You don’t have to write TypeScript code on Deno, but Deno is important because it’s written in the TypeScript language at its core:

First, more and more JavaScript programmers are falling in love with TypeScript.

Second, you’re using a tool that can easily infer a lot about software written in TypeScript languages, such as Deno.

As a result, the benefits of type checking and advanced IntelliSense come in time when coding in VS Code, an editor tightly integrated with TypeScript. In other words, editors can help us understand TypeScript projects in very useful ways.

Similarities and differences with Node.js

Since Deno is in some ways an alternative to Node.js, it’s helpful to compare the similarities and differences directly.

Similarities:

  • Both are based on V8 engines;
  • Both are ideal for writing JavaScript applications on the server side.

Differences:

  • Node.js is written in C++ and JavaScript. Deno is written in Rust and TypeScript languages.
  • Node.js has an official package manager called NPM. Deno won’t, but will allow you to import any ES module from the URL.
  • Node.js imports the software package using CommonJS module syntax. Deno is imported using the ES standard module.
  • Deno uses modern ECMAScript functionality in all of its apis and standard libraries, while Node.js uses the callbacks based standard library and has no plans to upgrade it.
  • Deno provides a secure sandbox environment through permission control, and programs can only access files that have been marked executable by the user. The node.js program can directly access anything the user can access.
  • Deno has long explored the possibility of compiling programs into a single executable that can run without external dependencies such as Go, but this is not an easy task and would be a powerful game-changer if done.

There is no package dependency manager

There are pros and cons to not having a package manager like NPM and relying heavily on urls to host and import packages. But I really like this feature: it will be so flexible that we can create packages directly without having to publish them in a repository like NPM.

There’s no official word yet, but I think some kind of package manager under Deno will appear.

At the same time, the Deno site provides code hosting services for third-party software packages (and helps distribute them via URLS) : see deno.land/x/ for more information.

Install Deno

So much for small talk! Let’s get started on installing Deno.

The easiest way to do this is to use Homebrew:

brew install deno
Copy the code

After you print the above command, you will have access to the deno command. Help is deno –help:

If HomeBrew is too slow to install, try manually turning off HomeBrew’s automatic update detection by typing the following command: export HOMEBREW_NO_AUTO_UPDATE=true

flavio@mbp~> deno --help
deno 0.42.0
A secure JavaScript and TypeScript runtime

Docs: https://deno.land/std/manual.md
Modules: https://deno.land/std/ https://deno.land/x/
Bugs: https://github.com/denoland/deno/issues

To start the REPL, supply no arguments:
  deno

To execute a script:
  deno run https://deno.land/std/examples/welcome.ts
  deno https://deno.land/std/examples/welcome.ts

To evaluate code in the shell:
  deno eval "console.log(30933 + 404)"

Run 'deno help run' for 'run'-specific flags.

USAGE:
    deno [OPTIONS] [SUBCOMMAND]

OPTIONS:
    -h, --help
            Prints help information

    -L, --log-level <log-level>
            Set log level [possible values: debug, info]

    -q, --quiet
            Suppress diagnostic output
            By default, subcommands print human-readable diagnostic messages to stderr.
            If the flag is set, restrict these messages to errors.
    -V, --version
            Prints version information


SUBCOMMANDS:
    bundle         Bundle module and dependencies into single file
    cache          Cache the dependencies
    completions    Generate shell completions
    doc            Show documentation for a module
    eval           Eval script
    fmt            Format source files
    help           Prints this message or the help of the given subcommand(s)
    info           Show info about cache or info related to source file
    install        Install script as an executable
    repl           Read Eval Print Loop
    run            Run a program given a filename or url to the module
    test           Run tests
    types          Print runtime TypeScript declarations
    upgrade        Upgrade deno executable to newest version

ENVIRONMENT VARIABLES:
    DENO_DIR             Set deno's base directory (defaults to $HOME/.deno) DENO_INSTALL_ROOT Set deno install's output directory
                         (defaults to $HOME/.deno/bin)
    NO_COLOR             Set to disable color
    HTTP_PROXY           Proxy address for HTTP requests
                         (module downloads, fetch)
    HTTPS_PROXY          Same but for HTTPS
Copy the code

Deno command

Note the SUBCOMMANDS section after deno –help in the previous section, which lists all the commands we can run in the current version (0.42.0), as follows:

  • bundle: Bundle the project’s modules and dependencies into a single file
  • cache: Cache dependencies;
  • completions: generate shell completions;
  • doc: Displays the document of a module;
  • eval: Run a piece of code, for exampledeno eval "console.log(1 + 2) ;
  • fmt: a built-in code formatter (similar to Gogofmt);
  • help: Prints the help information of a message or a command to the stator.
  • info: Displays information about caches or about source files;
  • install: Installs the script as an executable file.
  • repl: Enable the REPL environment (default subcommand).
  • run: Runs a program given a filename or URL;
  • test: Run tests;
  • types: Prints runtime TypeScript declarations;
  • upgrade: Upgrade Deno to the latest version.

You can run deno

help to get specific documentation for the subcommand, such as deno run –help.

As shown below, you can start the REPL (read-execute – print-loop) environment direct debugging by default by entering the deno command, which is the same as running the deno REPL.

A more common scenario for using deno commands directly is to execute deno applications written in TypeScript files.

Now you need to use the deno run command instead of the deno command to execute TypeScript files.

You can run TypeScript (.ts) files or JavaScript (.js) files simultaneously.

If you’re unfamiliar with TypeScript, don’t worry — Deno is written in TypeScript, and you can write “client” applications in pure JavaScript.

If you want to get started with TypeScript quickly, you can read my TypeScript tutorial.

Your first Deno app

Let’s run the first Deno application.

One of Deno’s most surprising features to me is that you can run a Deno application at any URL without even having to write a line of code.

At this point, Deno downloads the program from the URL to the local, compiles it, and then runs:

Of course, I generally don’t recommend running unsecured code from the Internet. In this case, we first run the Demo available on Deno’s official website; Deno also has a sandbox that prevents the program from doing things you don’t want to do. More on that later.

The program is simple. All it needs is a call to console.log() :

console.log("Welcome to Deno 🦕");
Copy the code

Deno. land/ STD /example… This URL, you will see the following page:

Strange, isn’t it? You might expect a plain TypeScript file to be downloaded when you open the URL, but instead we see a web page. The reason is that the Deno Web server knows you’re using a browser and provides you with more user-friendly pages.

To verify this, we can test the URL using the wget command, which downloads text using text/plain instead of text/ HTML:

If you want to run this program again, it is now cached by Deno, so you don’t need to download and compile it.

You can use the –reload parameter to force a re-download and compilation of the original source code.

In the current version (0.42.0), deno — Run has many features not listed in the deno –help listing. You need to run deno run –help to show more.

flavio@mbp~> deno run --help
deno-run
Run a program given a filename or url to the module.

By default all programs are run in sandbox without access to disk, network or
ability to spawn subprocesses.
  deno run https://deno.land/std/examples/welcome.ts

Grant all permissions:
  deno run -A https://deno.land/std/http/file_server.ts

Grant permission to read from disk and listen to network:
  deno run --allow-read --allow-net https://deno.land/std/http/file_server.ts

Grant permission to read whitelisted files from disk:
  deno run --allow-read=/etc https://deno.land/std/http/file_server.ts

USAGE:
    deno run [OPTIONS] <SCRIPT_ARG>...

OPTIONS:
    -A, --allow-all
            Allow all permissions

        --allow-env
            Allow environment access

        --allow-hrtime
            Allow high resolution time measurement

        --allow-net=<allow-net>
            Allow network access

        --allow-plugin
            Allow loading plugins

        --allow-read=<allow-read>
            Allow file system read access

        --allow-run
            Allow running subprocesses

        --allow-write=<allow-write>
            Allow file system write access

        --cached-only
            Require that remote dependencies are already cached

        --cert <FILE>
            Load certificate authority from PEM encoded file

    -c, --config <FILE>
            Load tsconfig.json configuration file

    -h, --help
            Prints help information

        --importmap <FILE>
            UNSTABLE:
            Load import map file
            Docs: https://deno.land/std/manual.md#import-maps
            Specification: https://wicg.github.io/import-maps/
            Examples: https://github.com/WICG/import-maps#the-import-map
        --inspect=<HOST:PORT>
            activate inspector on host:port (default: 127.0.0.1:9229)

        --inspect-brk=<HOST:PORT>
            activate inspector on host:port and break at start of user script

        --lock <FILE>
            Check the specified lock file

        --lock-write
            Write lock file. Use with --lock.

    -L, --log-level <log-level>
            Set log level [possible values: debug, info]

        --no-remote
            Do not resolve remote modules

    -q, --quiet
            Suppress diagnostic output
            By default, subcommands print human-readable diagnostic messages to stderr.
            If the flag is set, restrict these messages to errors.
    -r, --reload=<CACHE_BLACKLIST>
            Reload sourcecode cache (recompile TypeScript) --reload Reload everything --reload=https://deno.land/std Reload only standard modules  --reload=https://deno.land/std/fs/utils.ts,https://deno.land/std/fmt/colors.ts Reloads specific modules --seed <NUMBER>  Seed Math.random() --unstable Enable unstable APIs --v8-flags=<v8-flags> Set V8command line options. For help: --v8-flags=--help


ARGS:
    <SCRIPT_ARG>...
            script args
Copy the code

Deno code instance

In addition to the Demo we ran above, the Deno website provides some other examples, which can be viewed here: deno.land/ STD /example… .

You may need to configure the proxy for better access to DenoLand.

At the time of writing this manual, we can find:

  • cat.ts: The printed content is a list of files provided as parameters;
  • catj.ts: The printed content is a list of files provided as parameters;
  • chat/: An implementation of chat;
  • colors.tsPrint a color version of Hello World! ;
  • curl.ts: a simple implementation, curl, which prints the contents of the URL specified as a parameter;
  • echo_server.ts: TCP echo server;
  • gist.ts: a program to publish documents to gist.github.com;
  • test.ts: Sample test suite;
  • welcome.ts: a simple console.log statement (the first program we run on it);
  • xeval.ts: allows you to run any TypeScript code for any line of standard input you receive. It was designed to bedeno xevalSubcommands are now removed from official commands.

Your first Deno App (Deep Edition)

So let’s write some code.

Above perform deno run [https://deno.land/std/examples/welcome.ts] (https://deno.land/std/examples/welcome.ts) command execution is a deno provided by the website So we haven’t seen anything specific about what the Deno code looks like.

Let’s start with the default sample application listed on the official Deno website.

import { serve } from "https://deno.land/std/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}
Copy the code

This code imports the service function from the HTTP/Server module. As you can see, we don’t need to install these modules first, and we don’t store them in large quantities on the local machine as Node.js does. This is one of the reasons why Deno is so fast to install.

From [https://deno.land/std/http/server.ts] (https://deno.land/std/http/server.ts) to import initiation into the latest version of the module. You can import a specific VERSION using @version, as shown below.

import { serve } from "https://deno.land/[email protected]/http/server.ts";
Copy the code

The serve function is defined in this file as follows:

/** * Create a HTTP server * * import { serve } from "https://deno.land/std/http/server.ts"; * const body = "Hello World\n"; * const s = serve({ port: 8000 }); * for await (const req of s) { * req.respond({ body }); *} * /
export function serve(addr: string | HTTPOptions) :Server {
  if (typeof addr === "string") {
    const [hostname, port] = addr.split(":");
    addr = { hostname, port: Number(port) };
  }

  const listener = listen(addr);
  return new Server(listener);
}
Copy the code

We next instantiate a server, passing an object with a port property by calling the server() function.

Then we run the following loop to respond to each request from the server.

for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}
Copy the code

Note that we use the await keyword here without needing to encapsulate it in an asynchronous function because Deno implements top-level await support inside it.

Let’s run this program locally. Assuming you’re using VS Code (you can use any editor you like), I’d suggest starting with the Deno VS Code extension developed by JustJavac (there was an extension with the same name when I tried it, but it’s obsolete and will probably disappear in the future).

Justjavac’s Deno VS Code extension will be officially included, and you can use the official extension directly from now on.

This extension will provide VS Code with several utilities and nice things to help you write applications.

Now create an app.ts file in a folder and paste the code above.

Now run it with the deno run app.ts command.

Deno downloads and compiles the imported dependency and all of its required dependencies.

This is due to our import [https://deno.land/std/http/server.ts] (https://deno.land/std/http/server.ts) file itself several other rely on:

import { encode } from ".. /encoding/utf8.ts";
import { BufReader, BufWriter } from ".. /io/bufio.ts";
import { assert } from ".. /testing/asserts.ts";
import { deferred, Deferred, MuxAsyncIterator } from ".. /async/mod.ts";
import {
  bodyReader,
  chunkedBodyReader,
  emptyReader,
  writeResponse,
  readRequest,
} from "./_io.ts";
import Listener = Deno.Listener;
import Conn = Deno.Conn;
import Reader = Deno.Reader;
Copy the code

But Deno will automatically import it for us.

In the end, we have one more question.

What’s going on here? Why do we get the message that execution permission is denied?

That’s where Deno’s Sandbox comes in. Let’s take a look.

Deno Safety Sandbox

As I mentioned earlier, Deno has a security sandbox that prevents programs from doing things that you don’t allow.

What does that mean?

One of the things That Ryan mentioned in his presentation at Deno is that sometimes you want to run a JavaScript program outside of a Web browser, but you don’t want it to arbitrarily access anything it wants on your system, like using the Web to talk to the outside world.

Why do we usually only install Node.js packages from trusted sources? That’s because there’s nothing to stop the Node.js program from getting the SSH key or whatever else is on your system and sending it to the server. But how do we know if a project we or someone else is using has been hacked?

Deno’s solution is to try to implement the same permissions model heavily borrowed from browsers — any JavaScript running in a browser can’t do anything wrong on your system unless you explicitly allow it.

Going back to Deno, if a program wants to access the network as in the previous example, then we need to give it permissions.

We can do this by passing a flag when we run the command, in this case –allow-net.

deno run --allow-net app.ts
Copy the code

The application now listens for an HTTP server running on port 8000:

Other flags allow Deno to unlock other features, as shown below:

  • --allow-env: Allows access to environment variables;
  • --allow-hrtime: Allows high resolution time measurement;
  • --allow-net=<allow-net>: Allows network access.
  • --allow-plugin: Allows loading plug-ins;
  • --allow-read=<allow-read>: Permits the file system to read.
  • --allow-run: Allows child processes to run;
  • --allow-write=<allow-write>: Allows write access to the file system.
  • --allow-all: Allows all permissions (and-AThe same).

Net, read, and write permissions can be specific. For example, you can use –allow-read=/dev to allow reading from a specific folder.

Formatting code

One of my favorite features of Go is the gofmt command that comes with the Go compiler. The format of all Go code looks the same. Every Go programmer is using GoFmt.

While JavaScript programmers are used to running Prettier, deno FMT actually builds the libraries directly onto the Prettier tool.

Suppose you have a serious formatting problem with the file shown below.

You run deno FMT app.ts and it performs the correct code formatting, including automatically adding the missing semicolon.

The standard library

Despite its young age, Deno’s standard library is still huge. This includes:

  • archive: utility for tar file archiving
  • async: Asynchronous tool
  • bytes: helper to manipulate byte slices
  • datetime: Date/time parsing
  • encoding: Various formats of encoding/decoding
  • flags: Parses the command line flag
  • fmt: Format and print
  • fs: File system API
  • hashEncryption library:
  • http: HTTP server
  • io: I/O library
  • log: Logging utility
  • mime: Supports multiple types of data
  • node: Node.js compatibility layer
  • path: path control
  • ws: web sockets

Another Deno example

Let’s look at another example of a Deno APP, such as cat.ts.

const filenames = Deno.args;
for (const filename of filenames) {
  const file = await Deno.open(filename);
  await Deno.copy(file, Deno.stdout);
  file.close();
}
Copy the code

The value of deno. args is assigned to the filenames variable. Deno.args is a variable that contains all the arguments sent to the command.

We iterate over these parameters: for each parameter, we use deno.open () to open the file, and deno.copy () to print the contents of the file to deno.stdout, and finally we close the file.

If you use the following command:

deno run https://deno.land/std/examples/cat.ts
Copy the code

After the program was downloaded and compiled, nothing happened because we didn’t specify any arguments.

Now try this:

deno run https://deno.land/std/examples/cat.ts app.ts
Copy the code

Suppose you have app.ts from your previous project in the same folder.

You will get the following permission error.

This is because Deno does not allow access to file systems by default. You need to use the –allow-read=./ command to grant access to the current folder:

deno run --allow-read=./ https://deno.land/std/examples/cat.ts app.ts
Copy the code

Deno 是否有 Express/Hapi/Koa/*

B: of course. You can look at these libraries down here.

  • deno-drash
  • deno-express
  • oak
  • pogo
  • servest

Example: Building a REST-API with Oak

I want to do a simple hands-on Demo of how to build the REST API using the Oak framework. Oak is interesting because it was inspired by Koa, a popular Node.js middleware. Because of this, Oak will quickly become familiar to you if you’ve used Koa before.

The API example we will build is also very simple.

Our server will store a list of wangchai names and ages in memory.

Our requirements are:

  • Add wangchai;
  • List Wangchai;
  • Obtain detailed information about a particular wangchai;
  • A wangchai was removed from the list;
  • Update the age of wangchai.

We’ll do this with TypeScript, but there’s nothing to stop you from writing the API in JavaScript — you just need to remove all the type description code from the underlying TypeScript file and change the filename suffix to.js.

Create an app.ts file.

Let’s start importing the Application and Router objects from Oak:

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
Copy the code

Then we get the environment variables PORT and HOST:

const env = Deno.env.toObject();
const PORT = env.PORT || 4000;
const HOST = env.HOST || "127.0.0.1";
Copy the code

By default, our application will run on localhost: 4000.

Now let’s create the Oak application and launch it:

const router = new Router();

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Listening on port ${PORT}. `);

await app.listen(`${HOST}:${PORT}`);
Copy the code

The application should now compile properly.

deno run --allow-env --allow-net app.ts
Copy the code

Deno will then download the dependencies:

The program is listening on port 4000.

The next time you run this command, Deno will skip the installation because the packages are already cached.

At the top of the file, let’s define an interface to Wangchai, and then we declare an initial array of Dogs Dog objects.

interface Dog {
  name: string;
  age: number;
}

let dogs: Array<Dog> = [
  {
    name: "Roger",
    age: 8,
  },
  {
    name: "Syd",
    age: 7,},];Copy the code

Now, let’s implement the concrete API.

We’ve got everything ready. After you’ve created the router, let’s add some functions that will be called whenever one of these routes is triggered.

const router = new Router();

router
  .get("/dogs", getDogs)
  .get("/dogs/:name", getDog)
  .post("/dogs", addDog)
  .put("/dogs/:name", updateDog)
  .delete("/dogs/:name", removeDog);
Copy the code

See? Our API definition is:

  • GET /dogs
  • GET /dogs/:name
  • POST /dogs
  • PUT /dogs/:name
  • DELETE /dogs/:name

Let’s get started.

From start GET /dogs, it will return a list of all wangchai:

export const getDogs = ({ response }: { response: any }) = > {
  response.body = dogs;
};
Copy the code

Next, let’s look at how to retrieve Wangchai by name.

export const getDog = ({
  params,
  response,
}: {
  params: {
    name: string;
  };
  response: any; = > {})const dog = dogs.filter((dog) = > dog.name === params.name);
  if (dog.length) {
    response.status = 200;
    response.body = dog[0];
    return;
  }

  response.status = 400;
  response.body = { msg: `Cannot find dog ${params.name}` };
};
Copy the code

Here’s how we add a new wangchai:

export const addDog = async ({
  request,
  response,
}: {
  request: any;
  response: any; = > {})const body = await request.body();
  const dog: Dog = body.value;
  dogs.push(dog);

  response.body = { msg: "OK" };
  response.status = 200;
};
Copy the code

Note that I now use const body = await request.body() to get the content of the body because the name and age values are passed in JSON form.

Here’s how we updated the age of Wangchai:

export const updateDog = async ({
  params,
  request,
  response,
}: {
  params: {
    name: string;
  };
  request: any;
  response: any; = > {})const temp = dogs.filter((existingDog) = > existingDog.name === params.name);
  const body = await request.body();
  const { age }: { age: number } = body.value;

  if (temp.length) {
    temp[0].age = age;
    response.status = 200;
    response.body = { msg: "OK" };
    return;
  }

  response.status = 400;
  response.body = { msg: `Cannot find dog ${params.name}` };
};
Copy the code

Here’s how we removed Wangchai from the list:

export const removeDog = ({
  params,
  response,
}: {
  params: {
    name: string;
  };
  response: any; = > {})const lengthBefore = dogs.length;
  dogs = dogs.filter((dog) = >dog.name ! == params.name);if (dogs.length === lengthBefore) {
    response.status = 400;
    response.body = { msg: `Cannot find dog ${params.name}` };
    return;
  }

  response.body = { msg: "OK" };
  response.status = 200;
};
Copy the code

Here is the complete sample code:

import { Application, Router } from "https://deno.land/x/oak/mod.ts";

const env = Deno.env.toObject();
const PORT = env.PORT || 4000;
const HOST = env.HOST || "127.0.0.1";

interface Dog {
  name: string;
  age: number;
}

let dogs: Array<Dog> = [
  {
    name: "Roger",
    age: 8,
  },
  {
    name: "Syd",
    age: 7,},];export const getDogs = ({ response }: { response: any }) = > {
  response.body = dogs;
};

export const getDog = ({
  params,
  response,
}: {
  params: {
    name: string;
  };
  response: any; = > {})const dog = dogs.filter((dog) = > dog.name === params.name);
  if (dog.length) {
    response.status = 200;
    response.body = dog[0];
    return;
  }

  response.status = 400;
  response.body = { msg: `Cannot find dog ${params.name}` };
};

export const addDog = async ({
  request,
  response,
}: {
  request: any;
  response: any; = > {})const body = await request.body();
  const { name, age }: { name: string; age: number } = body.value;
  dogs.push({
    name: name,
    age: age,
  });

  response.body = { msg: "OK" };
  response.status = 200;
};

export const updateDog = async ({
  params,
  request,
  response,
}: {
  params: {
    name: string;
  };
  request: any;
  response: any; = > {})const temp = dogs.filter((existingDog) = > existingDog.name === params.name);
  const body = await request.body();
  const { age }: { age: number } = body.value;

  if (temp.length) {
    temp[0].age = age;
    response.status = 200;
    response.body = { msg: "OK" };
    return;
  }

  response.status = 400;
  response.body = { msg: `Cannot find dog ${params.name}` };
};

export const removeDog = ({
  params,
  response,
}: {
  params: {
    name: string;
  };
  response: any; = > {})const lengthBefore = dogs.length;
  dogs = dogs.filter((dog) = >dog.name ! == params.name);if (dogs.length === lengthBefore) {
    response.status = 400;
    response.body = { msg: `Cannot find dog ${params.name}` };
    return;
  }

  response.body = { msg: "OK" };
  response.status = 200;
};

const router = new Router();
router
  .get("/dogs", getDogs)
  .get("/dogs/:name", getDog)
  .post("/dogs", addDog)
  .put("/dogs/:name", updateDog)
  .delete("/dogs/:name", removeDog);

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Listening on port ${PORT}. `);

await app.listen(`${HOST}:${PORT}`);
Copy the code

More content

The official Deno website is deno.land.

The API documentation is located in doc.deno.land and deno.land/typedoc/ind… In the.

A list of Awesome Deno resources github.com/denolib/awe… .

The Chinese list of Awesome Deno is continuously maintained by the translator. You can visit here: The full map of Awesome Deno resources

trivia

  • Deno provides a built-infetchImplementation that matches what is available in the browser.
  • Deno is working on a compatibility layer with node.js stdlib

conclusion

I hope you enjoy this introduction to Deno!

Don’t forget, you can get the PDF/ePub/Mobi version of the Deno manual here.