Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Language and Runtime Basics

The Deno Namespace and Runtime APIs

Tour the Deno global object - version and build info, cwd, pid, memory, standard streams, typed errors, signals, and how to feature-detect APIs so your code stays portable.

The web platform gives you fetch, URL and friends. For everything a browser cannot do, Deno adds one global object called Deno. It holds the functions that read files, run processes, start servers, read environment variables and describe the runtime itself. This lesson tours the parts that are not about files or arguments (those get their own lessons: Reading and Writing Files and Command-Line Arguments and Environment Variables).

Deno is not available on this site, so Deno-only calls appear as read-only code with the output you would see. Runnable examples use Node.js equivalents or pure JavaScript, and say so.

What lives on Deno

The Deno namespace groups its API by purpose:

Area Examples
Runtime info Deno.version, Deno.build, Deno.pid, Deno.mainModule
Files Deno.readTextFile, Deno.writeTextFile, Deno.open, Deno.stat
Environment Deno.env, Deno.args, Deno.cwd, Deno.exit
Network Deno.serve, Deno.connect, Deno.listen
Processes Deno.Command
Testing Deno.test, Deno.bench
Data Deno.openKv
Errors and signals Deno.errors, Deno.addSignalListener

Type Deno. in your editor and look at the completion list: every entry has documentation. The online reference at docs.deno.com mirrors it.

Runtime information

TypeScript
console.log(Deno.version.deno);       // "2.1.4" for example
console.log(Deno.version.v8);         // V8 version
console.log(Deno.version.typescript); // bundled TypeScript
console.log(Deno.build.os);           // "linux", "darwin" or "windows"
console.log(Deno.build.arch);         // "x86_64" or "aarch64"
console.log(Deno.pid);                // process id
console.log(Deno.mainModule);         // URL of the entry file
console.log(Deno.cwd());              // current directory (needs --allow-read)

Deno.build.os is the right way to branch on the operating system, for example to pick a path separator or a shell command. Deno.noColor is true when the NO_COLOR variable is set, and well-behaved CLIs check it before printing colors.

The same kind of information exists in Node.js as process.versions, process.platform, process.arch and process.pid. The stand-in below prints them, so you can see the shape of this data. In Deno the names above replace these.

Node.js Runtime info (Node.js stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Standard input and output

console.log is a convenience over the standard streams. When you need raw access, Deno.stdin, Deno.stdout and Deno.stderr expose them, each with a readable or writable web stream:

TypeScript
const encoder = new TextEncoder();
await Deno.stdout.write(encoder.encode("no newline here"));

// read all of standard input as text
const input = await new Response(Deno.stdin.readable).text();
console.log(`you typed ${input.length} characters`);

Use console.error for diagnostics, so that program output (stdout) stays clean for pipes: deno run script.ts > result.txt keeps errors on the terminal.

Inspecting values

Deno.inspect(value) returns the same string that console.log would print, which is useful for logs and error messages:

TypeScript
const data = { name: "Ada", tags: new Set(["math", "code"]), when: new Date(0) };
console.log(Deno.inspect(data, { compact: true }));
TEXT
{ name: "Ada", tags: Set(2) { "math", "code" }, when: 1970-01-01T00:00:00.000Z }

Options include depth, colors, sorted and compact. Node.js has an equivalent in util.inspect, which makes a runnable demonstration:

Node.js Formatting values for logs (Node.js stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Typed errors

Failed system calls throw errors that belong to classes under Deno.errors. Catch them by class, not by comparing message text:

TypeScript
try {
  await Deno.readTextFile("missing.txt");
} catch (error) {
  if (error instanceof Deno.errors.NotFound) {
    console.log("file does not exist");
  } else if (error instanceof Deno.errors.NotCapable) {
    console.log("permission was not granted");
  } else {
    throw error; // not ours: rethrow
  }
}

Common classes are NotFound, AlreadyExists, PermissionDenied, NotCapable (a missing Deno permission), InvalidData, TimedOut, BrokenPipe and ConnectionRefused. The "rethrow what you do not understand" pattern is important: never swallow unknown errors.

The pattern is ordinary JavaScript, so you can practise it on any runtime by building your own error hierarchy:

Node.js Catching errors by class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Signals and shutdown

Servers and long jobs should stop cleanly when someone presses Ctrl+C or a process manager sends SIGTERM:

TypeScript
function shutdown() {
  console.log("closing connections...");
  Deno.exit(0);
}

Deno.addSignalListener("SIGINT", shutdown);
Deno.addSignalListener("SIGTERM", shutdown);

Signal support differs on Windows: only SIGINT, SIGBREAK and a few others exist there. A listener keeps the process alive, so remove it with Deno.removeSignalListener when you are done.

There are also the web events load, unload, beforeunload, error and unhandledrejection on globalThis, so addEventListener("unload", ...) runs cleanup right before the program exits.

Timers and the event loop

setTimeout, setInterval and queueMicrotask are the browser versions. A pending timer or open server keeps the process alive. You can opt a timer out of that with Deno.unrefTimer(id), handy for background housekeeping that should not block exit.

Writing portable code

If a library should work on Deno, Node.js and browsers, test for features instead of checking the runtime name:

TypeScript
const hasDeno = typeof Deno !== "undefined";
const readText = hasDeno
  ? (path: string) => Deno.readTextFile(path)
  : (path: string) => import("node:fs/promises").then((fs) => fs.readFile(path, "utf8"));

For new code, prefer web standard APIs when they exist (fetch, streams, URL) and reach for Deno.* only for system work. It keeps your code easy to move.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the operating system name in Deno?

    Deno.build.os returns linux, darwin or windows.
  2. 2. How should you detect that a file does not exist?

    System errors have typed classes; instanceof is reliable while messages can change.
  3. 3. What should you do with an error you do not recognise in a catch block?

    Swallowing unknown errors hides bugs. Rethrow what you cannot handle.
  4. 4. Which error means a Deno permission was not granted?

    NotCapable is thrown when an operation needs a permission the program does not have.

Summary

  • Deno holds system APIs; web APIs stay global.
  • Deno.version, Deno.build and Deno.pid describe the runtime.
  • Deno.inspect formats values like console.log.
  • Catch system errors by class (Deno.errors.NotFound, NotCapable) and rethrow others.
  • Use Deno.addSignalListener for clean shutdown.
  • Prefer web standards for portability and feature-detect the rest.

Next: Async Code and Top-Level Await