This document assumes that you have some prior knowledge of JavaScript,
especially about /await
. If you have no prior knowledge of JavaScript,
you might want to follow a guide
before attempting to start with Deno.
Deno is a runtime for JavaScript/TypeScript which tries to be web compatible and use modern features wherever possible.
Browser compatibility means a Hello World
program in Deno is the same as the
one you can run in the browser:
Try the program:
deno run https://deno.land/std@$STD_VERSION/examples/welcome.ts
Many programs use HTTP requests to fetch data from a webserver. Let’s write a small program that fetches a file and prints its contents out to the terminal.
Just like in the browser you can use the web standard
fetch
API to
make HTTP calls:
const url = Deno.args[0];
const res = await fetch(url);
await Deno.stdout.write(body);
- We get the first argument passed to the application, and store it in the
url
constant. - We make a request to the url specified, await the response, and store it in
the
res
constant. - We parse the response body as an
,
await the response, and convert it into a
Uint8Array
to store in thebody
constant. - We write the contents of the
body
constant tostdout
.
Try it out:
You will see this program returns an error regarding network access, so what did we do wrong? You might remember from the introduction that Deno is a runtime which is secure by default. This means you need to explicitly give programs the permission to do certain ‘privileged’ actions, such as access the network.
Try it out again with the correct permission flag:
deno run --allow-net=example.com https://deno.land/std@$STD_VERSION/examples/curl.ts https://example.com
Deno also provides APIs which do not come from the web. These are all contained
in the Deno
global. You can find documentation for these APIs on
.
Filesystem APIs for example do not have a web standard form, so Deno provides its own API.
In this program each command-line argument is assumed to be a filename, the file is opened, and printed to stdout.
const filenames = Deno.args;
for (const filename of filenames) {
const file = await Deno.open(filename);
file.close();
Try the program:
This is an example of a server which accepts connections on port 8080, and returns to the client anything it sends.
const hostname = "0.0.0.0";
const port = 8080;
const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) {
Deno.copy(conn, conn);
}
For security reasons, Deno does not allow programs to access the network without explicit permission. To allow accessing the network, use a command-line flag:
To test it, try sending data to it with netcat:
Like the cat.ts
example, the copy()
function here also does not make
unnecessary memory copies. It receives a packet from the kernel and sends it
back, without further complexity.
You can find more examples, like an HTTP file server, in the chapter.