Why Deno

There are two things that appeal to me

  • By default, ts and TSX are supported
  • Default security, control of permissions

Document portal:

Deno Official website denO Chinese tutorial

The installation

Shell (Mac, Linux):

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

PowerShell (Windows):

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

Homebrew (Mac):

brew install deno
Copy the code

Chocolatey (Windows):

choco install deno
Copy the code

Scoop (Windows):

scoop install deno
Copy the code

Build and install from source using Cargo

cargo install deno
Copy the code

Slower network speed can be used to install Chinese image

curl -fsSL https://x.deno.js.cn/install.sh | sh
Copy the code

An introduction to

Import {serve} from "https://deno.land/[email protected]/ 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 is using STD, STD is a standard module, you can’t use STD. STD portal

However, I highly recommend server, Oak, which is a library modeled after KOA. Oak portal

Before writing, let’s take a look at the style guide deno Style Guide portal for example

  • withmod.tsInstead ofindex.tsChange index to mod
  • Use underscores instead of dashes in file names
  • Top-level functions should not use arrow syntax (this should work even in non-deno, because if they are named functions, the editor can import them automatically without manually finding the path)

So before using Oak, let’s get the basic directory structure right (fYI)

–.vscode —- launch.json (editor configuration,vscode example) –modules —- oak (cache directory, not source code, But git should be added) — SRC (source code location) —-deps.ts (third party dependent main portal) —-mod.ts (code main portal) –test (test code location) deno Test document portal —-**test.ts —-**test.tsx –readme.md (Basic Introduction)

It is mainly composed of four parts

  • The development environment
  • Dependencies (caching)
  • The source code
  • test

Vscode configuration or other configuration see development debug portal

Vscode adds the launch.json file according to the configuration, and the file content is as follows

Configurations ": {"version": "0.2.0", "Configurations ": [{"name": "Debug Deno (Allow All)", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "runtimeExecutable": "deno", "runtimeArgs": [ "run", "--inspect-brk", "-A", "src/mod.ts", "test/mod.ts", ], "port": 9229, "console": "integratedTerminal" } ] }Copy the code

Add oak and mysql dependencies to deds.ts

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

(Due to deno official access restrictions, my portal can be github, deno_mysql portal if possible)

A little talk about ts types

(This is a third party module. The third party module will specify the type as follows.)

/// <reference types="./foo.d.ts" />
export const foo = "foo";
Copy the code

If we import a js file, then the d.ts file is introduced as follows, annotated as follows

// @deno-types="./foo.d.ts"
import * as foo from "./foo.js";
Copy the code

(This may seem silly, but the benefits are clarity and stability.)

See denO TS for details

Ok, we’ve written demos.ts, so let’s introduce it in mod. Ts.

import { Application, Router, Client } from "./deps.ts" const client = await new Client().connect({ hostname: IP address, username: "root", db: "", poolSize: 3, // connection limit password: "",}) const pcRouter = new Router() const app = new Application() pcRouter .prefix('/pc') .use(async (context, Return context.response.body = json.stringify ({MSG:}) {return context.response.body = json.stringify ({MSG:}); ''}) return next() }) .get("/banner/list", async (context) => { const list = await client.query(`select * from banner ORDER BY position DESC`) context.response.body = JSON.stringify(list) }) app.use((context, next) => { context.response.headers.set('Access-Control-Allow-Origin', '*') context.response.headers.set('Access-Control-Allow-Headers', '*') context.response.headers.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS') if(context.request.method == 'OPTIONS'){ context.response.status = 200 } return next() }) app.use(pcRouter.routes()) console.log("http://localhost:10086") await app.listen({ port: 10086 })Copy the code

Write the code and run it

Before running, we need to set the cache directory location, if Windows, then can be opened in ps (ps how to open? Windows key +R, type Powershell enter) inside Settings

$Env:DENO_DIR = "F:\deno\< project >\modules"Copy the code

Perform caching after completion

deno cache -r --lock=lock.json src/deps.ts
Copy the code

Finally, execute in the root directory

deno run  --allow-net  .\src\mod.ts
Copy the code

Allow-net is implemented because deno is secure by default, so you need to allow networks, otherwise files, networks, etc., will not be implemented.

By this time visit http://localhost:10086/pc/banner/list, you can get them by list.

Ok, good entry.

Use the editor to debug

After setting the above launch.json, we can automatically start it by pressing f5 in vscode. The permission is also the highest, you can edit the json file if you want to modify it. (If it cannot be started, you may have modified the port. Do not modify the port.)

Then you can have fun, as shown in the interruption point

By the way, there is a very important thing, that is how to implement denO, because denO and TS files js files, TSX files are still by the difference.

At this point we can install the plug-in. Let me install the vscode deno plug-in

More editor deno development plugins

Ok, everything is fine, but when we go back to other projects, we will find red errors everywhere, because the ts, js and other files are parsed by the deno plugin. We need to start it only in the Deno project, so we can disable deno in other projects.

To disable the function, perform the following steps

Others:

Download error

For domestic reasons as well as DNS contamination, dependencies cannot be downloaded well as follows“That” does not work globally, so we need to modify the host file and add it to the host file

199.232.68.133 	raw.githubusercontent.com
Copy the code

Do not know how to modify the host file, see: Windows how to modify the host file

Debug error tolerance

The reason is that –inspect-brk is enabled, but the port does not match. The default value 9229 can be changed

db

Not only denomysQL, but also Denodb, which is an excellent library, DenoDB will support PostgreSQL, MySQL, MariaDB, SQLite and MongoDB, DenoDB portals. however, denod_mysql will be smaller and more MySQL focused

Mysql syntax document mysql rookie tutorial

oak

In addition to Oak, there is ABC (also written by Chinese), the Portal

request

Deno complies with browser specifications, supporting setTimeout, Blob, Worker, FormData, etc. Requests can use Fetch, and documents can directly see the Fetch portal on MDN

Use NPM package

Deno also supports Node, which has a module underneath it that supports creating a require function like this

import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
Copy the code

So here we have the require function, if that’s familiar.

To get the plugin

To obtain plug-ins, search deno.land/x/ here

Such as

  • Redis: deno. Land/x/redis \
  • jwt: deno.land/x/djwt

– the –