Impression Deno

In 2018, what do you think of ry’s project Deno’s issue that was splashed in Chinese? “Successfully brought Deno to my attention, and CNode wrote a scathing article that called it a shame on Chinese developers, which I can’t quite agree with, since it’s hard to incubate a foreign spirit of innovation in the context of 996. But I do not deny that learning to learn the action, all depends on the individual. I recently the most admired snail old wet _ big saint insist every day more than 5 o ‘clock get up, so diligent and durable, why worry about learning not to move?

Why Deno?

1, heat, although the problem of learning not to move caused a negative impact, but deno successfully earned enough gimmick and traffic.

2, trend, we can clearly see in the figure below, since the establishment of Deno in 2018, has achieved nearly 70K star, especially after the release of 1.0 on 2020-05-13, is ushered in a wave of peak.

3, gold exploration essay activity, the last boiling point activity was lucky to get a luxury lift table, but WHAT I want most is actually the gold surrounding gift package.

What is Deno?

  • Deno is a simple, modern, and secure JavaScript and TypeScript runtime environment based on the V8 engine and built in the Rust programming language.
  • Deno was created by Ryan Dahl, author of Node.js.

Function highlights

  • Default security Settings. Unless explicitly enabled, there are no files, no network, and no access to the running environment.
  • Built-in support for TypeScript.
  • There is only a single executable file.
  • Built-in utilities, such as dependency checker (deno Info) and code formatting tool (deno FMT).
  • A set of audited (audited) standard modules to ensure compatibility with Deno: DENO. land/ STD
  • The script code can be packaged as a separate JavaScript file.
  • Decentralized Package: no node_modules or package.json; The Package is loaded via the URL –deno.land/x/; Cache to disk when loading
  • Top Level Await: Write code in Deno without wrapping the Await in an asynchronous function. How sweet!
  • Others: built-in tests, browser-compatible apis, execution of Wasm binaries, Modern JS, ES Modules

Why Deno?

Deno: De (Destroy) no(Node)

  1. Dropped native support for Promise: Caused core API aging issues that had to be updated to the Promise version.

  2. Not thinking carefully about security: Using NODE.js with V8 doesn’t require “authorization” to access networks, file systems, and even memory information, which is one of the issues with Node.js that will be questioned in an era when data security considerations are increasingly important

  3. Build System: In the early days of Node development, Chrome V8 was built on GYP, and Node used GYP, but soon Chrome switched from GYP to GN, and Node was no longer able to recover. As a result, Node is currently the only user using GYP on V8, and GN is nearly 20 times faster than GYP, has readable files, and supports many dependencies.

  4. Package.json and Npm centralization issues

  5. Node_modules: There is no standard for each of the folders in node_modules, so you can put extra versions or any other files and files, which adds complexity to module parsing. Another community that has been suffering node_modules for a long time, ridiculed for being blacker than a black hole:

  1. Index.js: With package.json, there is no need to load index.js by default, which really complicates module loading.

With this in mind, RY decided to develop a modern JavaScript runtime that takes advantage of the latest features of JavaScript and browsers. For more questions, check out the resources talk.

Fears that Deno is killing Node.js

When Deno was first launched, there was a lot of chatter about whether or not it would replace Node.js. I think living in the moment (NodeJs) and preparing for the future (Deno) is the best attitude.

  • Nodejs is far from being replaced
  • Nodejs is very mature and has a huge ecosystem
  • Deno is a brand new technology, and it’s likely to get more attention as a competitor to NodeJS in the coming years
  • Deno is an excellent alternative to tooling scripts written in bash or Python in the past.

Environment to prepare

Deno has no external dependencies to a single can execute file publishing. You can install Deno using the installer below, or you can download the published binary executable from the release page first.

Download and install

Using a Shell (Mac, Linux) :

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

Using PowerShell (Windows) :

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

Use the Homebrew (Mac) :

$ brew install deno
Copy the code

Test the installation

  • Run deno -v. If it prints out the denO version, the installation is successful.

  • Run deno Help to view the help documentation.

  • Run deno help

    to see the options for the subcommand.

Relative path

  • DENO_DIR location (Deno installation location) : “/ Users/yangjunning/Library/Caches/Deno”
  • Remote modules cache (Remote module cache) : “/ Users/yangjunning/Library/Caches/deno deps”
  • TypeScript compiler cache (TypeScript compile cache) : “/ Users/yangjunning/Library/Caches/deno/gen”

upgrade

To upgrade an installed version, run:

deno upgrade
Copy the code

This from github.com/denoland/de… Get the latest release, then unzip and replace the existing version.

You can also use this to install a specific version:

Deno upgrade - version 1.0.1Copy the code

IDE and plug-in

Recommended to use VSCode and VSCode Deno development, VSCode Deno is developed by justJavac.

To resolve conflicts with other normal Node projects, create a.vscode/settings.json file in your project and fill in the following configuration:

{
  "deno.enable": true.// set false for user setting
  "editor.formatOnSave": true."[typescript]": {
    "editor.defaultFormatter": "denoland.vscode-deno"}},Copy the code

Quick learning

Hello World

Try running this simple program:

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

Setting up a file server

$Deno run --allow-read --allow-net https://deno.land/[email protected]/ HTTP /file_server.ts
Copy the code

Create an HTTP server

Create a file named index.ts

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

Run the deno run XXX command to execute the file:

$Deno run --allow-net --reload index.ts // --reload is used by the cache module the first time
Copy the code

Make an HTTP request

It is common to get data from the server via HTTP requests. Let’s write a simple program to fetch the file and print it to the terminal.

Just like a browser, you can use the Web standard FETCH API to make requests.

// We take the first command-line argument and store it in the variable URL.
const url = Deno.args[0];
// We send a request to the specified address, wait for the response, and then store it in the variable res.
const res = await fetch(url);

// We parse the response body into an ArrayBuffer, wait for it to be received, convert it into Uint8Array and store it in the body variable.
const body = new Uint8Array(await res.arrayBuffer());
// We write the body contents to the standard output stream stdout.
await Deno.stdout.write(body);
Copy the code
$ deno run --allow-net sendHttp.ts http://example.com/ / or$ deno run --allow-net=example.com https://deno.land/std/examples/curl.ts https://example.com
Copy the code

Write a file

const encoder = new TextEncoder();
const greetText = encoder.encode("Hello World\nMy name is youngjuning!")

await Deno.writeFile("greet.txt", greetText)
Copy the code

Read a file

Deno also provides built-in apis, which are located in the global variable Deno. You can find the documentation here: doc.deno.land.

The file system API does not have a Web standard form, so Deno provides a built-in API.

In this program, each command line argument is a file name, and the files corresponding to the arguments are successively opened and printed to the standard output stream.

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

Except for the necessary copy from kernel to user space and back to kernel, the copy() function here does not produce any additional expensive operations, and the data read from the file is written to the standard output stream as is. This reflects the general design goal of Deno I/O streams.

Try it:

$ deno run cat.ts /etc/passwd
Copy the code

TCP service

Create a new cat.ts. This example is a TCP Echo service that receives connections on port 8080 and returns any data it receives to the client.

const hostname = "127.0.0.1";
const port = 8080;
const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) {
  Deno.copy(conn, conn);
}
Copy the code

Try to send data to it using Netcat.

Like the example cat.ts, the copy() function does not make an unnecessary copy of memory. It receives packets from the kernel and sends them back, simple as that.

Dependency management

Importing urls anywhere doesn’t seem convenient. What if one of those urls links to a slightly different version of the library? In a large project, is maintaining urls error-prone? The solution is to import and re-export the external libraries in the central deps.ts file (for the same purpose as Node’s package.json file). For example, suppose you are using the above test library in a large project. Do not import “deno.land/ STD /testing… Deps.ts, used to export third-party code:

export * from "https://deno.land/std/http/server.ts"; / / recommend
export * as Server from "https://deno.land/std/http/server.ts";
export { default as Server } from "https://deno.land/std/http/server.ts";
Copy the code

It can be imported from deps.ts throughout the project to avoid multiple references to the same URL:

import {test, assertEquals} from './deps.ts';
Copy the code

This design avoids excessive complexity due to package management software, a centralized code base, and redundant file formats.

packaging

Deno Bundle comes with packaging and Tree Shaking to package our code into a single file

#! /bin/sh
deno bundle ./src/index.ts ./dist/index.js
Copy the code

Deno Install can generate executable files from our code for direct use

#! /bin/sh
deno install --allow-read  --allow-net --allow-write -n youngjuning ./src/index.ts
Copy the code

We also can install remote library: directly deno install – allow – read – allow -.net, https://deno.land/std/http/file_server.ts

Deno executable files by default in/Users/yangjunning /. Deno/bin/directory, we need to register it into the environment variables:

$ export PATH="/Users/yangjunning/.deno/bin:$PATH"
Copy the code

permissions

We already know that Deno is safe by default. So the Deno module has no access to files, networks, or environments unless you authorize it. You must authorize the denO process in the command line to access security-sensitive functions.

Permissions list

The following permissions are available:

  • -A.--allow-all: Allows all permissions, which disables all security restrictions.
  • --allow-env: Allows environment access, such as reading and setting environment variables.
  • --allow-hrtime: Allows high precision time measurement, which can be used in timing attacks and feature recognition.
  • --allow-net=<allow-net>: Allows network access. You can specify a series of comma-separated domain names to provide a whitelist of domain names.
  • --allow-plugin: Allows plug-ins to be loaded. Please note: this is an unstable feature.
  • --allow-read=<allow-read>Allows file system reading. You can specify a series of comma-separated directories or files to provide a file system whitelist.
  • --allow-runAllows child processes to run. Please note that child processes do not run in a sandbox and therefore do not have the same security restrictions as denO processes, so use with caution.
  • --allow-write=<allow-write>Allows writing to the file system. You can specify a series of comma-separated directories or files to provide a file system whitelist.

Permission whitelist

Deno also allows you to use whitelists to control the granularity of permissions.

This is an example of whitelisting file system access to allow access only to the /usr directory, but it will fail when trying to access the /etc directory.

–allow-write, too, represents write permission.

Network access

fetch.ts:

const result = await fetch("https://deno.land/");
Copy the code

Here is an example of setting a host or URL whitelist:

$ deno run --allow-net=github.com,deno.land fetch.ts
Copy the code

The process will fail if fetch. Ts attempts to establish a network connection with another domain.

Allow access to any address:

$ deno run --allow-net fetch.ts
Copy the code

The plugin is recommended

denv

A dotenv – like plugin for Deno

use

You can import it directly, and then use the.env file in its sibling directory:

import { load } from "https://deno.land/x/denv/mod.ts";
await load();
console.log(Deno.env.get("HOME"));  // e.g. outputs "/home/alice"
console.log(Deno.env.get("MADE_UP_VAR"));  // outputs "Undefined"
Copy the code

Env File rules

The rules are the same as dotenv except that double letter values expand new lines are not implemented.

packaging

Deno Bundle comes with packaging and Tree Shaking to package our code into a single file

$ deno bundle ./src/index.ts ./dist/index.js
Copy the code

Deno Install can generate executable files from our code for direct use

$deno install --allow-read --allow-net --allow-write -n youngjuning ./src/index.ts
Copy the code

Deno executable files by default in/Users/yangjunning /. Deno/bin/directory, we need to register it into the environment variables:

$ export PATH="/Users/yangjunning/.deno/bin:$PATH"
Copy the code

FAQ

1, the problem of permission identifier location

As we all know, deno is secure by default, which means that by default it is not allowed to access the network, read or write files, etc. For example, there is a file named index.ts with the following contents:

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

If you run deno run index.ts, you will hear an error:

Error: Uncaught PermissionDenied: network access to "0.0.0.0:8000", run again with the --allow-net flagCopy the code

So it’s natural to add –allow-net to the end of the startup command, as follows:

$ deno run index.ts --allow-net
Copy the code

However, you will still get an error. –allow-net, –allow-read, etc. –allow-net, –allow-read, etc.

$ deno run --alow-net index.ts
Copy the code

2. Remote module cache

  1. The remote code is fetched the first time it is run and cached until the code passes--reloadRefresh the cache. (So it works on an airplane).
  2. Modules or files loaded from remote urls should be immutable and cacheable.

The resources

  • 10 Things I regret about Node.js – Ryan Dahl-jsconf EU 2018
  • Deno Quick Start Guide
  • Deno Runtime Tutorial: Alternatives to Node.js
  • Deeply understand the design errors of -Nod-js – reflect on the speech of -Ryan -Dahl
  • Ryan Dahl: I don’t want to be defined
  • Deno Chinese website
  • Deno Chinese community

🏆 technology project phase I | talk about Deno some thing…