Deno has officially launched 🎉!

No matter how the outside is blowing, or how deprecating, in short, is the mule is the horse out of the walk, understand before you have the right to speak. Let’s get started on deno in 20 minutes!

start

The installation

Due to the speed of the Internet in China, @justJavac made a mirror acceleration in China:

Mac/Linux

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

Windows

iwr https://x.deno.js.cn/install.ps1 -useb -outf install.ps1; .\install.ps1
# iwr https://x.deno.js.cn/install.ps1 -useb | iex
Copy the code

Setting environment variables

Deno doesn’t have a node_modules directory in node as a place to store packages, but it does need a place to have installed modules:

DENO_DIR, which defaults to $HOME/. Deno, is the path where deno stores generated code and cached source code.

# mac / linux
echo 'export DENO_DIR=$HOME/.deno' >> ~/.bash_profile
source ~/.bash_profile # if ZSH: source ~/.zshrc
Copy the code

Install the VSCode plug-in

Since the import URL form and Deno global object are not supported by VSCode, we need to use the plugin Deno to support them:

Note: You need to set deno.enabled to true in Settings

Before the installation:

After the installation:

hello world

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

If nothing else, you’ll see:

The Compile Download https://deno.land/std/examples/welcome.ts https://deno.land/std/examples/welcome.ts Welcome to Deno 🦕Copy the code

If you do this again, you will see that the Download and Compile processes are gone, and the result is directly:

Welcome to Deno 🦕
Copy the code

in-depth

Deno built-in API use

First let’s look at an example of reading a file directory:

const dir = Deno.readDirSync(Deno.cwd())
for (const file of dir) {
	console.log(file)
}
Copy the code

Deno.cwd() means the current directory, deno.readdirSync means to read the directory and return an iterable, which we use for output. Run the following command to see the result:

deno run --allow-read mod.ts
Copy the code

First, we see that deno does not use imported modules like Node does. Instead, we use global deno objects. We can see all the built-in apis as output:

console.log(Deno);
Copy the code

We use the VSCode plugin to click on the Deno object to jump to its TS definition:

If you don’t understand English, you can refer to or replace the Chinese version.

If you still don’t feel intuitive, refer to TypeDoc: Chinese or English

Support for TS

In Deno, TS and JS are both first class citizens and can be supported perfectly. Such as:

// index.ts
let name: string = 'ry'
name = 123
Copy the code
> deno run index.ts
Copy the code

The results of

Compile file:///Users/zhangchaojie/Desktop/demo/index.ts
error: TS2322 [ERROR]: Type '123' is not assignable to type 'string'.
name = 123;
~~~~
    at file:///Users/zhangchaojie/Desktop/demo/index.ts:2:1
Copy the code

permissions

By default, Deno does not have network, file read, file write, and environment variable read permissions.

// index.js
// Get the data
fetch('http://jsonplaceholder.typicode.com/posts/1')
.then((res) = > res.json())
.then((data) = > {
	console.log(data)
})
Copy the code
deno run index.js
Copy the code

After execution, a string of errors is found:

error: Uncaught PermissionDenied: network access to "http://jsonplaceholder.typicode.com/posts/1", run again with the --allow-net flag
Copy the code

Let’s try adding permissions:

deno run --allow-net index.js
{
 userId: 1,
 id: 1,
 title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
 body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas..."
}
Copy the code

If you feel uncomfortable, you can use the -a parameter to allow full permissions.

import URL

Deno has no node_modules, no package.json, and uses import urls to refer to third-party modules:

import { white, bgRed } from "https://deno.land/std/fmt/colors.ts";

console.log(bgRed(white("Hello world")));
Copy the code
deno run --allow-net mod.ts Compile file:///Users/zhangchaojie/Desktop/demo/mod.ts Download https://deno.land/std/fmt/colors.ts: hello, world# Pretend to have color
Copy the code

Although seemingly simple, but also careful you will find a lot of problems:

1. Slow Compile and Download process?

It only downloads the first time it’s executed, then caches it, and when you re-execute it, it’s still pretty fast:

Deno Run mod. Ts Hello world# Pretend to have color
Copy the code

2. What if there is no Internet?

After the first download, Deno will cache the file in the environment variable $HOME/. Deno.

tree $HOME/. Deno/Users/zhangchaojie /. Deno ├ ─ ─ deps │ └ ─ ─ HTTPS │ └ ─ ─ deno. Land │ ├ ─ ─ 3574883 d8acbaf00e28990ec8e83d71084c4c668c1dc7794be25208c60cfc935 │ └ ─ ─ 3574883 d8acbaf00e28990ec8e83d71084c4c668c1dc7794be25208c60cfc935. Metadata. Json └ ─ ─ gen#...

13 directories, 8 files
Copy the code

If you need to deploy your code to an environment where there is no Internet access, you can simply copy the contents of this directory to the corresponding directory and specify environment variables to the directory.

Of course, if you are installing a third-party dependency, for example, https://deno.land goes down, then GG is the only option (PS: very unlikely, just like npmjs.com goes down, you can’t install the package).

3. How do I update dependencies?

If the dependency file has been updated, we can use the –reload command to update it. We can also whitelist only some of the dependencies:

deno run --reload=https://deno.land mod.ts
Copy the code

An asynchronous operation returns a Promise

Asynchronous operations in Deno are returned Promise objects and support top-level-await, for example:

const file = await Deno.create("./foo.txt");
console.log(file);
Copy the code

Standard module

Deno offers developers a practical, high-frequency development library with no external dependencies to ease our development burden:

  • Node: Node API compatible module;
  • IO: binary read and write operations.
  • HTTP: The network is related to Web services;
  • Path: file path related;
  • Colors: Output text with colors, similar to chalk library;
  • Printf: Formatted output, similar to C printf;
  • Tar: decompresses and compresses.
  • Async: generating asynchronous functions;
  • Bytes: binary comparison and search.
  • Datetime: Date related;
  • Encoding: text and binary conversion, CSV and object conversion, YARML and object conversion, etc.
  • Flags: Command line argument parsing;
  • Hash: convert characters to SHA1 and SHA256.
  • Fs: File system module, similar to the FS module of Node;
  • Log: Log management;
  • Permissions: permissions related;
  • Testing: Testing is related to assertions;
  • Uuid: Used to generate a UUID.
  • Ws: WebSocket related;

The library will be continuously improved and expanded according to actual needs, and everyone can contribute their own strength.

Built-in tools

With the idea of developing dependencies in mind, Deno provides a set of practical tools:

  • Deno bundle: packages files
  • Deno FMT: formats
  • Deno Lint: Code checking (not implemented yet)
  • Deno test: test

Deno bundle:

You can think of it as a webpack file:

// foo.js
const obj = { name: 'foo' }
export default obj
Copy the code
# packaged
deno bundle foo.js foo.bundle.js
Copy the code
// Index.js imports the packaged file
import foo from './foo.bundle.js'
console.log(foo)
Copy the code
deno run index.js
{ name: "foo" }
Copy the code

Deno FMT:

You can think of Prettier as “Prettier” :

Create a file
Note the space on the left
echo "console.log( 'foo')" > index.js
Copy the code
# format
deno fmt index.js
Copy the code
# View files
cat index.js
console.log("foo"); # Left space without 😊
Copy the code

Deno test: You can interpret this as Jest functionality:

// Introduce the assertion module
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";

Deno.test("hello test", () = > {const x = 'hello' + ' test';
  assertEquals(x, 'hello test');
});
Copy the code

Learning and Materials

  • Official website: authoritative first-hand information;
  • Getting Started: from understanding to getting started;
  • Standard module: the source of all things;
  • Third party module: Heroes gather;
  • Domestic installation acceleration: farewell installation slow;
  • Chinese handbook: Good News for English sleepers;
  • Ts definition Chinese: as above, the Definition of TS in Chinese.