Starting from scratch -Deno

Let’s talk about history

Deno is a JavaScript/TypeScript runtime that executes code in a secure environment by default and has an excellent development experience. Deno has the following features:

  1. Security by default. External code has no file system, network, or environment access unless explicitly enabled.
  2. Support for TypeScript out of the box.
  3. Distribute only a single executable (denO).
  4. There are built-in toolkits, such as a dependency viewer (deno Info) and a code formatter (deno FMT).
  5. There is a standard set of audited modules that are guaranteed to work on Deno.
  6. Script code can be packaged as a single JavaScript file.

Organization chart for Deno

Deno’s organizational structure changes iteratively over time, and learning an evolving new language gives you a better view of things

Deno Preparations

The installation

Deno installation

Basic concept understanding

Deno standard module

Deno provides a set of standard modules that are reviewed by the core team and guaranteed to be used with Deno. Deno’s official advice for using standard modules is as follows:

These modules will eventually be tagged according to the Deno release, but as of now, we don’t think they’re stable

Do not link to/import any module with the following path:

  • A name or parent prefixed with an underscore:_foo ts, _util/bar. Ts.
  • That is a test module or test data:Test. ts, foo_test.ts, testdata/bar.txt.
  • Do not import any symbols prefixed with underscoresexport function _baz() {}.

These elements are not considered part of the public API and therefore cannot be guaranteed stability

Deno’s built-in toolbox

Deno provides a rich toolbox of functions, including script according to, code formatting check, generate JSDOC and other rich functions, this article will gradually introduce the need to use the tool functions of Deno.

Deno FMT # Format all JS/TS files in current and subdirectories deno FMT # format specific files deno FMT file1.ts file2. TS # Check if all JS/TS files in current and subdirectories are formatted deno FMT --check # Check ES module and all dependencies deno info [URL]Copy the code

Get started on your first Hello Word

Start by setting up an HTTP service

For setting up a service, Deno standard library provides a Server function for setting up a simple HTTP service. Importing the listenAndServe function from Deno’s standard library passes in the port number and the handler for the request.

// server.ts
import { listenAndServe } from 'https://deno.land/std/http/server.ts'
listenAndServe({ port: 3000 }, async (req) => {
  if (req.method === 'GET' && req.url === '/') {
    req.respond({
      status: 200.headers: new Headers({
        'content-type': 'text/html',}).body: await Deno.open('./index.html'),})}})console.log('Server running on localhost:3000')
Copy the code

The Server is analysed. The ts

The Server organization tree gives you the functions and classes to know, ListenAndServe starts the HTTP Server with the given options and request handler,Serve is used to create a Server,_parseAddrFromStr is a utility function used to convert strings into objects,Server This part is the essence of THE Deno HTTP implementation module. This section will be described in detail in the denO module analysis.

├─ Class ├─ class ├─ class ├─ class ├─ class ├─ class ├─ class ├─ class ├─ class ├─ class ├─ class ├─ class ├─Copy the code
export async function listenAndServe(
  addr: string | HTTPOptions,
  handler: (req: ServerRequest) => void.) :Promise<void> {
  const server = serve(addr);

  for await (const request ofserver) { handler(request); }}Copy the code

The listenAndServe method passes the ADDR and handler. Addr as the HTTP-related configuration option and handler as the handler function on the ServerRequest request object.

export function serve(addr: string | HTTPOptions) :Server {
  if (typeof addr === "string") {
    addr = _parseAddrFromStr(addr);
  }

  const listener = Deno.listen(addr);
  return new Server(listener);
}
Copy the code

The serve method passes addr. If addr is passed as a string, the _parseAddrFromStr method is called to convert the string to an HTTPOptions object. Deno.listen(), which returns a generic network listener for stream-oriented protocols as a global function, is passed as an argument to the constructor of the Server class, and the resulting Server instance object is passed to the asynchronous iterator for await of. The iterator will be passed to the handler function after the Promise is resolved.

export class Server implements AsyncIterable<ServerRequest> {
  private closing = false;
  private connections: Conn[] = [];
  constructor(public listener: Listener) {}
  close(): void {}
  private async *iterateHttpRequests(conn: Conn):AsyncIterableIterator<ServerRequest> {}
  private trackConnection(conn: Conn): void {}
  private untrackConnection(conn: Conn): void {}
  private async *acceptConnAndIterateHttpRequests(mux: MuxAsyncIterator<ServerRequest>): AsyncIterableIterator<ServerRequest> {}
  [Symbol.asyncIterator](): AsyncIterableIterator<ServerRequest> {}
}
Copy the code