Deno quick start

Table of contents

1 Introduction

2. Install Deno

Installation under MacOS

Installation under Windows

Installation under Linux

3. Create and run TypeScript programs

4. Built-in Web API and Deno namespace

5. Runtime security

6. Import JavaScript module

7. Remote module and Deno standard library

8. Configure your project using deno.json

9. Node.js API and npm package

10. Configure IDE


1 Introduction

Deno is a JavaScript, TypeScript, and WebAssembly runtime with safe defaults and a great developer experience. It is based on the V8 engine, Rust and tokio.

Deno is a free open source software based on MIT license.

2. Install Deno

Installation under MacOS

curl -fsSL https://deno.land/x/install/install.sh | sh

Installation under Windows

Open the Windows Power Shell that comes with the system, and then execute the following command:

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

Installation under Linux

curl -fsSL https://deno.land/x/install/install.sh | sh

After the installation is complete, you can check the current Deno version, as well as the dependent v8 version and ts version, as shown below:

deno --version

3. Create and run TypeScript programs

While you're welcome to use pure JavaScript, Deno also has built-in TypeScript support. In your terminal, create a new file called first.ts and contain the following code.

let name: string = `张三`;
let age: number = 18;
let result = `我的名字是${name},年龄是${age}
明年我就${age+1}岁了`;
console.log(result)
// 我的名字是张三,年龄是18
// 明年我就19岁了

Run the following command to view the corresponding output:

deno run first.ts

4. Built-in Web API and Deno namespace

Deno aims to provide a browser-like programming environment that implements Web standard APIs and front-end JavaScript. For example, the V8 engineAPI is available globally, just like in the browser. To see this, create a filehello.ts,with the following content:

const site = await fetch("https://www.deno.com");
console.log(await site.text());

Then run it:

deno run -A hello.ts

For APIs that do not exist as web standards (such as accessing variables from the system environment or manipulating the file system), these APIs will be exposed in the Deno namespace. Replaced content hello.tsUsing the following code, it will start the HTTP server, which will start the 8000 interface.

Deno.serve((_request: Request) => {
  return new Response("Hello, world!");
});

The result is shown below;

Start a local server and keep listening on port 8000. Then we can request it through a command to see if the corresponding result is returned, as shown below:

Then, it is found that the corresponding results have been output. There is an upgrade prompt in the picture above. Run deno upgrade to upgrade:

5. Runtime security

A key feature of Deno is runtime-by-default security, which means that as a developer, you must explicitly allow your code to access potentially sensitive APIs such as file system access, network connections, and environment variable access.

Until now, we have been running all scripts with the -A flag, which grants all runtime-specific access to our scripts. This is the most permissive mode for running Deno programs, but generally you only want to grant the code the permissions it needs to run.

To see this, let's stick with the contents of hello.ts above.

Run this program without the -A flag - what happens then?

In the prompt, you may have noticed that it mentions the CLI flags required to run the code to access the network - the--allow-net flag. If you run the script again with this flag, you will not be prompted to interactively grant network access to the script:

deno run --allow-net hello.ts

6. Import JavaScript module

Most of the time, you'll want to break your program into multiple files. Deno once again supports web standards and browser-like programming models, supporting this through the ECMAScript module. Here is a TypeScript example:

For example, there is a Hello.ts file with the following content:
 

interface Animal {
    name: string,
}
 
interface AnimalInter extends Animal {
    getInfo() : string
}
 
class Cat implements AnimalInter{ 
    birthday: Date;
    name: string;
    getInfo() {
        return this.name + ", " + this.birthday;
    }
    constructor(name: string, birthday: Date) {
        this.name = name;
        this.birthday = birthday;
    }
}
 
let result = new Cat('张三', new Date('2023-02-09'))
console.log('result: ', result.getInfo());

We can split the Animal-related parts into a separate file, such as Animal.ts, with the content as follows:

interface Animal {
    name: string,
}
 
export default interface AnimalInter extends Animal {
    getInfo() : string
}

Then create a file named Cat.ts with the following content:

import AnimalInter from "./Animal.ts";
class Cat implements AnimalInter{ 
    birthday: Date;
    name: string;
    getInfo() {
        return this.name + ", " + this.birthday;
    }
    constructor(name: string, birthday: Date) {
        this.name = name;
        this.birthday = birthday;
    }
}
 
let result = new Cat('张三', new Date('2023-02-09'))
console.log('result: ', result.getInfo());

This module can be used via the import keyword. Then run the cat.ts file and check the corresponding output:

deno run cat.ts

7. Remote module and Deno standard library

Deno supports loading and executing code from URLs, just like using the <script> tag in a browser. In Deno 1.x, the standard library and most third-party modulesDistributed over HTTPS URLs.

To see it in action, let's create a test for the module we createdCat.ts Above Deno provides a built-in test runner
, using Assertion module distributed via HTTPS URL.

Create a file named cat_test.ts with the following content:

import { assertEquals } from "https://deno.land/[email protected]/assert/mod.ts";
import Cat from "./Cat.ts";

Deno.test("Test function", () => {
  const cat: Cat =new Cat('张三', new Date('2023-02-09'));
  assertEquals("张三, Thu Feb 09 2023 08:00:00 GMT+0800 (中国标准时间)", cat.getInfo());
});

Run the following command and see the result of the corresponding assertion as follows:

deno test cat_test.ts

We found that the result of the assertion is as expected. If we change the expected result

assertEquals("张三1212, Thu Feb 09 2023 08:00:00 GMT+0800 (中国标准时间)", cat.getInfo());

We can see from the picture above that the expected value is inconsistent with the result returned by the method.

8. Configure your project using deno.json

Deno projects don't require configuration files by default, but sometimes it's convenient to store settings, management scripts, and dependent configurations in well-known locations. In Deno, this file is deno.json or deno.json. This file behaves somewhat like the pack.json file in Node.js.

You can use deno.json to configure import mappings, which will allow you to set aliases for commonly used modules.

For demonstration purposes, let's set the standard library version to be used in our project to version 0.204.0.

Create a filedeno.jsonc containing the following content.

{
  "imports": {
    "$std/": "https://deno.land/[email protected]/"
  }
}

Now, open the previous test file and change it to use this import alias.

import { assertEquals } from "$std/assert/mod.ts";
import Cat from "./Cat.ts";

Deno.test("Test function", () => {
  const cat: Cat =new Cat('张三', new Date('2023-02-09'));
  assertEquals("张三, Thu Feb 09 2023 08:00:00 GMT+0800 (中国标准时间)", cat.getInfo());
});

We found that the running result was the same as before, and a deno.lock file was generated in the current directory. This file specifies a set of files that the code depends on, as shown below:

9. Node.js API and npm package

Deno provides a compatibility layer that enables your code to use Node.js built-in modules and third-party modules from npm. Using Node and npm modules in code looks a lot like using standard Deno modules, except that you use the node: or npm: specifiers when importing Node built-in modules or npm respectively. module.

To see how it works, create a file called server.js and include it. Below is a simple HTTP server using the popular Expressframework.

import express from "npm:express@4";

const app = express();

app.get("/", (request, response) => {
  response.send("Hello from Express!");
});

app.listen(3000);

Running the code, the result looks like this:

10. Configure IDE

Deno is developed in many IDEs. A popular choice is Visual Studio Code, the official extension team maintained by Deno  Install the extension  and enable it in the VS Code workspace by selecting  Deno: Initialize Workspace Configuration option.
First, in VSCode, search for Deno in the extensions tab and choose to install it.
Then, open the command control panel, search for Deno, and configure the Deno workspace.

Guess you like

Origin blog.csdn.net/u014388408/article/details/133878591