Four sources to import modules in Deno
Modules are important for code reuse. Modules are useful in code organization, avoids code duplication & reinventing the wheel. Deno supports ES modules only. The only exception is to allow common JS style of importing when Deno runs in node compatibility mode.
Deno can use modules from four possible sources:
- Core modules
- Standard library
- Registered third-party modules
- Unregistered third-party modules
In this article, we’ll go over all the four possible sources to import modules from.
1. Core modules
Like Node.js, Deno comes with a set of core platform functionality. These cover the absolute basic functionalities like: HTTP, file I/O, file system ops, child process, etc. Unlike Node.js, where core modules needs importing, Deno’s core modules are part of the global Deno namespace that gets loaded at the startup. The core modules can be used direclty with Deno.<api-name>. Therefore, the core modules don’t need any importing.
Deno namespace
Here is an abbreviated list of the core APIs present inside the Deno namespace:
close, metrics, test, run, isatty, writeFileSync, writeFile, writeTextFileSync, writeTextFile, readTextFile, readTextFileSync, readFile, readFileSync, watchFs, chmodSync, chmod, chown, chownSync, copyFileSync, cwd, makeTempDirSync, makeTempDir, makeTempFileSync, makeTempFile, mkdirSync, mkdir, chdir, copyFile, readDirSync, readDir, readLinkSync, readLink, realPathSync, realPath, removeSync, remove, renameSync, rename, version, build, statSync, lstatSync, stat, lstat, truncateSync, …….. and so on
To get a full list of all the core APIs, the global Deno object can be printed:
$ deno eval "Deno" -p
core: {
opcallSync: [Function: opcallSync],
opcallAsync: [Function: opcallAsync],
refOp: [Function: refOp],
unrefOp: [Function: unrefOp],
setMacrotaskCallback: [Function: setMacrotaskCallback],
.....
}
pid: 8832,
ppid: 74629,
noColor: false,
args: [],
mainModule: [Getter],
Here are some examples of using core APIs:
//Print command-line args
Deno.args; //Reads a file as string
await Deno.readTextFile("/var/tmp/testdata/sample.txt");//Opens a file for reading
Deno.openSync("/var/tmp/testdata/sample.txt");//Quits the application
Deno.exit(1);
Window namespace
Additionally, there is a global namespace, called window, that contains all the web compatible APIs. Some examples are: web storage APIs, web crypto functions, web fetch, web file reader, etc. The Deno namespace is present inside the window namespace:
Window {
queueMicrotask: [Function: queueMicrotask],
dispatchEvent: [Function: dispatchEvent],
addEventListener: [Function: addEventListener],
removeEventListener: [Function: removeEventListener],
AbortSignal: [Function: AbortSignal],
AbortController: [Function: AbortController],
atob: [Function: atob],
btoa: [Function: btoa],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
crypto: Crypto {},
fetch: [Function: fetch],
performance: Performance {},
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout],
structuredClone: [Function: structuredClone],
location: [Getter/Setter],
window: [Circular],
self: [Circular],
navigator: [Getter],
close: [Function: windowClose],
closed: [Getter],
alert: [Function: alert],
confirm: [Function: confirm],
prompt: [Function: prompt],
localStorage: [Getter],
sessionStorage: [Getter],
onload: [Getter/Setter],
onunload: [Getter/Setter],
Deno: {
<<The deno namespace>>
}
}
The APIs present in the window namespace are globally accessible by calling the API directly. Here are some examples of using window APIs:
//Makes an HTTP request
await fetch("http://localhost:8000");//Converts a string to base64
btoa('Hello, world');//Number of CPUs
navigator.hardwareConcurrency;
2. Standard library
Deno’s standard library’s modules do not have external dependencies. They are always reviewed by the Deno core team. The purpose is to make a standard set of high quality modules that all Deno projects can use with trust. The GitHub repo for the standard library modules is here. Although the standard library is published by the Deno team, it is not a part of the core runtime. All the standard library modules needs explicit import.
Let’s have a look at some examples:
//Removes all the files from a directoryimport { emptyDir } from "https://deno.land/std/fs/mod.ts";await emptyDir("/var/tmp/testdata/someDir");//Asynchronous sleep for given msimport {delay} from "https://deno.land/std/async/mod.ts";await delay(5000);
Some very commonly used functionality like HTTP serve API is also a part of the standard library:
//Hello world HTTP serverimport { serve } from "https://deno.land/std/http/mod.ts";serve(() => new Response("Hello world!"), { port: 9000 });
3. Registered third-party modules
The third-party modules are those that are not provided or reviewed by Deno’s core team. Though not reviewed by Deno, these modules can still be registered with Deno’s third-party module service: deno.land/x. The deno.land/x is a hosting service for Deno scripts. It caches releases of open source modules stored on GitHub and serves them at one easy to remember domain.
For any registered module, Deno caches all the module releases into Deno’s S3 storage. This ensures that the registered third-party modules are always available. The module versions are persistent and immutable. It is thus not possible to edit or delete a module (or version), to prevent breaking programs that rely on this module.
The registered third-party modules can be imported from deno.land/x/<module>. Here are some examples:
//Tail a fileimport { Tail } from "https://deno.land/x/tail@1.1.0/mod.ts";const tail = new Tail("./someFile.txt");
for await (const line of tail.start()) {
console.log(line);
}//Generate a random number
import randomNumber from "https://deno.land/x/random_number/mod.ts";randomNumber();
4. Unregistered third-party modules
The unregistered third-party modules are those that Deno is not aware of. They can be hosted anywhere in the world. They can be imported from anywhere like local files, intranet files, GitHub, public and private CDNs, etc. There may not any guarantee of the availability of the versions of the unregistered module or even the module itself.
Here are some examples of using unregistered modules:
//Generate a cryptographically strong random stringimport {getRandomString} from "https://raw.githubusercontent.com/mayankchoubey/deno-random-id/main/mod.ts";getRandomString(50);
//ea4849017656ad512ab9fcf328bbce900dc0cc89676b6d4d24