summaryrefslogtreecommitdiff
path: root/docs/examples
diff options
context:
space:
mode:
Diffstat (limited to 'docs/examples')
-rw-r--r--docs/examples/fetch_data.md12
-rw-r--r--docs/examples/file_server.md53
-rw-r--r--docs/examples/file_system_events.md36
-rw-r--r--docs/examples/hello_world.md13
-rw-r--r--docs/examples/http_server.md38
-rw-r--r--docs/examples/import_export.md72
-rw-r--r--docs/examples/manage_dependencies.md29
-rw-r--r--docs/examples/module_metadata.md68
-rw-r--r--docs/examples/os_signals.md50
-rw-r--r--docs/examples/read_write_files.md60
-rw-r--r--docs/examples/subprocess.md41
-rw-r--r--docs/examples/tcp_echo.md40
-rw-r--r--docs/examples/testing_if_main.md10
-rw-r--r--docs/examples/unix_cat.md28
14 files changed, 441 insertions, 109 deletions
diff --git a/docs/examples/fetch_data.md b/docs/examples/fetch_data.md
index ad47e90b1..737ce29cf 100644
--- a/docs/examples/fetch_data.md
+++ b/docs/examples/fetch_data.md
@@ -1,5 +1,15 @@
# Fetch Data
+## Concepts
+
+- Like browsers, Deno implements web standard APIs such as
+ [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
+- Deno is secure by default, meaning explicit permission must be granted to
+ access the network
+- See also: Deno's [permissions](../getting_started/permissions.md) model
+
+## Overview
+
When building any sort of web application developers will usually need to
retrieve data from somewhere else on the web. This works no differently in Deno
than in any other JavaScript application, just call the the `fetch()` method.
@@ -12,6 +22,8 @@ prohibited. To make a call over the web Deno must be explicitly told it is ok to
do so. This is achieved by adding the `--allow-net` flag to the `deno run`
command.
+## Example
+
**Command:** `deno run --allow-net fetch.ts`
```js
diff --git a/docs/examples/file_server.md b/docs/examples/file_server.md
index 4559b5e3d..7235c84ad 100644
--- a/docs/examples/file_server.md
+++ b/docs/examples/file_server.md
@@ -1,22 +1,63 @@
-## File server
+# File server
-This one serves a local directory in HTTP.
+## Concepts
+
+- Use the Deno standard library
+ [file_server.ts](https://deno.land/std@$STD_VERSION/http/file_server.ts) to
+ run your own file server and access your files from your web browser
+- Run [Deno install](../tools/script_installer.md) to install the file server
+ locally
+
+## Example
+
+Serve a local directory via HTTP. First install the remote script to your local
+file system. This will install the script to the Deno installation root's bin
+directory, e.g. `/home/alice/.deno/bin/file_server`.
```shell
deno install --allow-net --allow-read https://deno.land/std@$STD_VERSION/http/file_server.ts
```
-Run it:
+You can now run the script with the simplified script name. Run it:
```shell
$ file_server .
Downloading https://deno.land/std@$STD_VERSION/http/file_server.ts...
[...]
-HTTP server listening on http://0.0.0.0:4500/
+HTTP server listening on http://0.0.0.0:4507/
```
-And if you ever want to upgrade to the latest published version:
+Now go to [http://0.0.0.0:4507/](http://0.0.0.0:4507/) in your web browser to
+see your local directory contents.
+
+## Help
+
+Help and a complete list of options are available via:
```shell
-file_server --reload
+file_server --help
+```
+
+Example output:
+
+```
+Deno File Server
+ Serves a local directory in HTTP.
+
+ INSTALL:
+ deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts
+
+ USAGE:
+ file_server [path] [options]
+
+ OPTIONS:
+ -h, --help Prints help information
+ -p, --port <PORT> Set port
+ --cors Enable CORS via the "Access-Control-Allow-Origin" header
+ --host <HOST> Hostname (default is 0.0.0.0)
+ -c, --cert <FILE> TLS certificate file (enables TLS)
+ -k, --key <FILE> TLS key file (enables TLS)
+ --no-dir-listing Disable directory listing
+
+ All TLS options are required when one is provided.
```
diff --git a/docs/examples/file_system_events.md b/docs/examples/file_system_events.md
index 2999ccdfe..1d483b4a0 100644
--- a/docs/examples/file_system_events.md
+++ b/docs/examples/file_system_events.md
@@ -1,18 +1,40 @@
-## File system events
+# File system events
-To poll for file system events:
+## Concepts
+
+- Use [Deno.watchFs](https://doc.deno.land/builtin/stable#Deno.watchFs) to watch
+ for file system events
+- Results may vary between operating systems
+
+## Example
+
+To poll for file system events in the current directory:
```ts
-const watcher = Deno.watchFs("/");
+/**
+ * watcher.ts
+ */
+const watcher = Deno.watchFs(".");
for await (const event of watcher) {
console.log(">>>> event", event);
- // { kind: "create", paths: [ "/foo.txt" ] }
+ // Example event: { kind: "create", paths: [ "/home/alice/deno/foo.txt" ] }
}
```
+Run with:
+
+```shell
+deno run --allow-read watcher.ts
+```
+
+Now try adding, removing and modifying files in the same directory as
+`watcher.ts`.
+
Note that the exact ordering of the events can vary between operating systems.
This feature uses different syscalls depending on the platform:
-- Linux: inotify
-- macOS: FSEvents
-- Windows: ReadDirectoryChangesW
+- Linux: [inotify](https://man7.org/linux/man-pages/man7/inotify.7.html)
+- macOS:
+ [FSEvents](https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html)
+- Windows:
+ [ReadDirectoryChangesW](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw)
diff --git a/docs/examples/hello_world.md b/docs/examples/hello_world.md
index 90a833f71..e1097497d 100644
--- a/docs/examples/hello_world.md
+++ b/docs/examples/hello_world.md
@@ -1,5 +1,12 @@
# Hello World
+## Concepts
+
+- Deno can run JavaScript or TypeScript out of the box with no additional tools
+ or config required
+
+## Overview
+
Deno is a secure runtime for both JavaScript and TypeScript. As the hello world
examples below highlight the same functionality can be created in JavaScript or
TypeScript, and Deno will execute both.
@@ -12,6 +19,9 @@ and the code ensures the name provided is capitalized.
**Command:** `deno run hello-world.js`
```js
+/**
+ * hello-world.js
+ */
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
@@ -44,6 +54,9 @@ rather than a `*.js` file.
**Command:** `deno run hello-world.ts`
```ts
+/**
+ * hello-world.ts
+ */
function capitalize(word: string): string {
return word.charAt(0).toUpperCase() + word.slice(1);
}
diff --git a/docs/examples/http_server.md b/docs/examples/http_server.md
new file mode 100644
index 000000000..21a9f8b5b
--- /dev/null
+++ b/docs/examples/http_server.md
@@ -0,0 +1,38 @@
+# Simple HTTP web server
+
+## Concepts
+
+- Use the std library [http module](https://deno.land/std@$STD_VERSION/http) to
+ run your own web server
+
+## Overview
+
+With just a few lines of code you can run your own http web server with control
+over the response status, request headers and more.
+
+## Sample web server
+
+In this example, the user-agent of the client is returned to the client
+
+```typescript
+/**
+ * webserver.ts
+ */
+import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts";
+
+const server = serve({ hostname: "0.0.0.0", port: 8080 });
+console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
+
+for await (const request of server) {
+ let bodyContent = "Your user-agent is:\n\n";
+ bodyContent += request.headers.get("user-agent") || "Unknown";
+
+ request.respond({ status: 200, body: bodyContent });
+}
+```
+
+Run this with:
+
+```shell
+deno run --allow-net webserver.ts
+```
diff --git a/docs/examples/import_export.md b/docs/examples/import_export.md
index 37ee8de06..7be14997b 100644
--- a/docs/examples/import_export.md
+++ b/docs/examples/import_export.md
@@ -1,5 +1,17 @@
# Import and Export Modules
+## Concepts
+
+- [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
+ allows you to include and use modules held elsewhere, on your local file
+ system or remotely.
+- Imports are URLs or file system paths
+- [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)
+ allows you to specify which parts of your module are accessible to users who
+ import your module
+
+## Overview
+
Deno by default standardizes the way modules are imported in both JavaScript and
TypeScript using the ECMAScript 6 `import/export` standard.
@@ -27,6 +39,9 @@ In this example the `add` and `multiply` functions are imported from a local
**Command:** `deno run local.ts`
```ts
+/**
+ * local.ts
+ */
import { add, multiply } from "./arithmetic.ts";
function totalCost(outbound: number, inbound: number, tax: number): number {
@@ -44,33 +59,6 @@ console.log(totalCost(45, 27, 1.15));
*/
```
-## Export
-
-In the example above the `add` and `multiply` functions are imported from a
-locally stored arithmetic module. To make this possible the functions stored in
-the arithmetic module must be exported.
-
-To do this just add the keyword `export` to the beginning of the function
-signature as is shown below.
-
-```ts
-export function add(a: number, b: number): number {
- return a + b;
-}
-
-export function multiply(a: number, b: number): number {
- return a * b;
-}
-```
-
-All functions, classes, constants and variables which need to be accessible
-inside external modules must be exported. Either by prepending them with the
-`export` keyword or including them in an export statement at the bottom of the
-file.
-
-To find out more on ECMAScript Export functionality please read the
-[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).
-
## Remote Import
In the local import example above an `add` and `multiply` method are imported
@@ -84,6 +72,9 @@ no problem handling this.
**Command:** `deno run ./remote.ts`
```ts
+/**
+ * remote.ts
+ */
import {
add,
multiply,
@@ -103,3 +94,30 @@ console.log(totalCost(45, 27, 1.15));
* 82.8
*/
```
+
+## Export
+
+In the local import example above the `add` and `multiply` functions are
+imported from a locally stored arithmetic module. To make this possible the
+functions stored in the arithmetic module must be exported.
+
+To do this just add the keyword `export` to the beginning of the function
+signature as is shown below.
+
+```ts
+/**
+ * arithmetic.ts
+ */
+export function add(a: number, b: number): number {
+ return a + b;
+}
+
+export function multiply(a: number, b: number): number {
+ return a * b;
+}
+```
+
+All functions, classes, constants and variables which need to be accessible
+inside external modules must be exported. Either by prepending them with the
+`export` keyword or including them in an export statement at the bottom of the
+file.
diff --git a/docs/examples/manage_dependencies.md b/docs/examples/manage_dependencies.md
index 142d66bac..f90a5fbd5 100644
--- a/docs/examples/manage_dependencies.md
+++ b/docs/examples/manage_dependencies.md
@@ -1,5 +1,16 @@
# Managing Dependencies
+## Concepts
+
+- Deno uses URLs for dependency management
+- One convention places all these dependent URLs into a local `deps.ts` file.
+ Functionality is then exported out of `deps.ts` for use by local modules.
+- Continuing this convention, dev only dependencies can be kept in a
+ `dev_deps.ts` file.
+- See also [Linking to external code](../linking_to_external_code.md)
+
+## Overview
+
In Deno there is no concept of a package manager as external modules are
imported directly into local modules. This raises the question of how to manage
remote dependencies without a package manager. In big projects with many
@@ -11,15 +22,17 @@ file. All required remote dependencies are referenced in this file and the
required methods and classes are re-exported. The dependent local modules then
reference the `deps.ts` rather than the remote dependencies.
-This enables easy updates to modules across a large codebase and solves the
-'package manager problem', if it ever existed. Dev dependencies can also be
-managed in a separate `dev_deps.ts` file.
+With all dependencies centralized in `deps.ts`, managing these becomes easier.
+Dev dependencies can also be managed in a separate `dev_deps.ts` file, allowing
+clean separation between dev only and production dependencies.
-**deps.ts example**
+## Example
```ts
/**
- * deps.ts re-exports the required methods from the remote Ramda module.
+ * deps.ts
+ *
+ * This module re-exports the required methods from the dependant remote Ramda module.
**/
export {
add,
@@ -32,9 +45,13 @@ In this example the same functionality is created as is the case in the
of the Ramda module being referenced directly it is referenced by proxy using a
local `deps.ts` module.
-**Command:** `deno run dependencies.ts`
+**Command:** `deno run example.ts`
```ts
+/**
+ * example.ts
+ */
+
import {
add,
multiply,
diff --git a/docs/examples/module_metadata.md b/docs/examples/module_metadata.md
new file mode 100644
index 000000000..8d2d92b50
--- /dev/null
+++ b/docs/examples/module_metadata.md
@@ -0,0 +1,68 @@
+# Module metadata
+
+## Concepts
+
+- [import.meta](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta)
+ can provide information on the context of the module
+- The boolean
+ [import.meta.main](https://doc.deno.land/builtin/stable#ImportMeta) will let
+ you know if the current module is the program entry point
+- The string [import.meta.url](https://doc.deno.land/builtin/stable#ImportMeta)
+ will give you the URL of the current module
+- The string
+ [Deno.mainModule](https://doc.deno.land/builtin/stable#Deno.mainModule) will
+ give you the URL of the main module entry point, i.e. the module invoked by
+ the deno runtime
+
+## Example
+
+The example below uses two modules to show the difference between
+`import.meta.url`, `import.meta.main` and `Deno.mainModule`. In this example,
+`module_a.ts` is the main module entry point
+
+```ts
+/**
+ * module_b.ts
+ */
+export function outputB() {
+ console.log("Module B's import.meta.url", import.meta.url);
+ console.log("Module B's mainModule url", Deno.mainModule);
+ console.log(
+ "Is module B the main module via import.meta.main?",
+ import.meta.main,
+ );
+}
+```
+
+```ts
+/**
+ * module_a.ts
+ */
+import { outputB } from "./module_b.ts";
+
+function outputA() {
+ console.log("Module A's import.meta.url", import.meta.url);
+ console.log("Module A's mainModule url", Deno.mainModule);
+ console.log(
+ "Is module A the main module via import.meta.main?",
+ import.meta.main,
+ );
+}
+
+outputA();
+console.log("");
+outputB();
+```
+
+If `module_a.ts` is located in `/home/alice/deno` then the output of
+`deno run --allow-read module_a.ts` is:
+
+```
+Module A's import.meta.url file:///home/alice/deno/module_a.ts
+Module A's mainModule url file:///home/alice/deno/module_a.ts
+Is module A the main module via import.meta.main? true
+
+Module B's import.meta.url file:///home/alice/deno/module_b.ts
+Module B's mainModule url file:///home/alice/deno/module_a.ts
+Is module B the main module via import.meta.main? false
+```
diff --git a/docs/examples/os_signals.md b/docs/examples/os_signals.md
index 3b2411bde..e4d7bc43a 100644
--- a/docs/examples/os_signals.md
+++ b/docs/examples/os_signals.md
@@ -1,37 +1,83 @@
-## Handle OS Signals
+# Handle OS Signals
> This program makes use of an unstable Deno feature. Learn more about
> [unstable features](../runtime/stability.md).
-[API Reference](https://doc.deno.land/https/raw.githubusercontent.com/denoland/deno/master/cli/dts/lib.deno.unstable.d.ts#Deno.signal)
+## Concepts
+
+- Use the `--unstable` flag to access new or unstable features in Deno
+- [Deno.signal](https://doc.deno.land/builtin/unstable#Deno.signal) can be used
+ to capture and monitor OS signals
+- Use the `dispose()` function of the Deno.signal
+ [SignalStream](https://doc.deno.land/builtin/unstable#Deno.SignalStream) to
+ stop watching the signal
+
+## Async iterator example
You can use `Deno.signal()` function for handling OS signals:
```ts
+/**
+ * async-iterator-signal.ts
+ */
+console.log("Press Ctrl-C to trigger a SIGINT signal");
for await (const _ of Deno.signal(Deno.Signal.SIGINT)) {
console.log("interrupted!");
+ Deno.exit();
}
```
+Run with:
+
+```shell
+deno run --unstable async-iterator-signal.ts
+```
+
+## Promise based example
+
`Deno.signal()` also works as a promise:
```ts
+/**
+ * promise-signal.ts
+ */
+console.log("Press Ctrl-C to trigger a SIGINT signal");
await Deno.signal(Deno.Signal.SIGINT);
console.log("interrupted!");
+Deno.exit();
```
+Run with:
+
+```shell
+deno run --unstable promise-signal.ts
+```
+
+## Stop watching signals
+
If you want to stop watching the signal, you can use `dispose()` method of the
signal object:
```ts
+/**
+ * dispose-signal.ts
+ */
const sig = Deno.signal(Deno.Signal.SIGINT);
setTimeout(() => {
sig.dispose();
+ console.log("No longer watching SIGINT signal");
}, 5000);
+console.log("Watching SIGINT signals");
for await (const _ of sig) {
console.log("interrupted");
}
```
+Run with:
+
+```shell
+deno run --unstable dispose-signal.ts
+```
+
The above for-await loop exits after 5 seconds when `sig.dispose()` is called.
diff --git a/docs/examples/read_write_files.md b/docs/examples/read_write_files.md
index a4f37f22e..ff1240e55 100644
--- a/docs/examples/read_write_files.md
+++ b/docs/examples/read_write_files.md
@@ -1,16 +1,34 @@
# Read and Write Files
-Interacting with the filesystem to read and write files is a basic requirement
-of most development projects. Deno provides a number of ways to do this via the
+## Concepts
+
+- Deno's runtime API provides the
+ [Deno.readTextFile](https://doc.deno.land/builtin/stable#Deno.readTextFile)
+ and
+ [Deno.writeTextFile](https://doc.deno.land/builtin/stable#Deno.writeTextFile)
+ asynchronous functions for reading and writing entire text files
+- Like many of Deno's APIs, synchronous alternatives are also available. See
+ [Deno.readTextFileSync](https://doc.deno.land/builtin/stable#Deno.readTextFileSync)
+ and
+ [Deno.writeTextFileSync](https://doc.deno.land/builtin/stable#Deno.writeTextFileSync)
+- Deno's [standard library]() provides additional functionality for file system
+ access, for example reading and writing JSON
+- Use `--allow-read` and `--allow-write` permissions to gain access to the file
+ system
+
+## Overview
+
+Interacting with the filesystem to read and write files is a common requirement.
+Deno provides a number of ways to do this via the
[standard library](https://deno.land/std) and the
[Deno runtime API](https://doc.deno.land/builtin/stable).
As highlighted in the [Fetch Data example](./fetch_data) Deno restricts access
-to Input / Output by default for security reasons. So when interacting with the
-filesystem the `--allow-read` and `--allow-write` flags must be used with the
-`deno run` command.
+to Input / Output by default for security reasons. Therefore when interacting
+with the filesystem the `--allow-read` and `--allow-write` flags must be used
+with the `deno run` command.
-## Read
+## Reading a text file
The Deno runtime API makes it possible to read text files via the
`readTextFile()` method, it just requires a path string or URL object. The
@@ -18,7 +36,10 @@ method returns a promise which provides access to the file's text data.
**Command:** `deno run --allow-read read.ts`
-```js
+```typescript
+/**
+ * read.ts
+ */
async function readFile(path: string): Promise<string> {
return await Deno.readTextFile(new URL(path, import.meta.url));
}
@@ -44,7 +65,7 @@ and provides methods to read and parse files. The `readJson()` and
JSON. All these methods require is a valid file path string which can be
generated using the `fromFileUrl()` method.
-In the example below the `readJsonSync()` method is used, for asynchronus
+In the example below the `readJsonSync()` method is used. For asynchronous
execution use the `readJson()` method.
Currently some of this functionality is marked as unstable so the `--unstable`
@@ -52,7 +73,10 @@ flag is required along with the `deno run` command.
**Command:** `deno run --unstable --allow-read read.ts`
-```js
+```typescript
+/**
+ * read.ts
+ */
import { readJsonSync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts";
import { fromFileUrl } from "https://deno.land/std@$STD_VERSION/path/mod.ts";
@@ -74,7 +98,7 @@ console.log(readJson("./people.json"));
*/
```
-## Write
+## Writing a text file
The Deno runtime API allows developers to write text to files via the
`writeTextFile()` method. It just requires a file path and text string. The
@@ -85,17 +109,20 @@ command.
**Command:** `deno run --allow-write write.ts`
-```js
+```typescript
+/**
+ * write.ts
+ */
async function writeFile(path: string, text: string): Promise<void> {
return await Deno.writeTextFile(path, text);
}
const write = writeFile("./hello.txt", "Hello World!");
-write.then(() => console.log("File written to."));
+write.then(() => console.log("File written to ./hello.txt"));
/**
- * Output: File written to.
+ * Output: File written to ./hello.txt
*/
```
@@ -107,7 +134,7 @@ This requires a combination of the `ensureFile()`, `ensureFileSync()`,
`writeJson()` and `writeJsonSync()` methods. In the example below the
`ensureFileSync()` and the `writeJsonSync()` methods are used. The former checks
for the existence of a file, and if it doesn't exist creates it. The latter
-method then writes the object to the file as JSON. If asynchronus execution is
+method then writes the object to the file as JSON. If asynchronous execution is
required use the `ensureFile()` and `writeJson()` methods.
To execute the code the `deno run` command needs the unstable flag and both the
@@ -115,7 +142,10 @@ write and read flags.
**Command:** `deno run --allow-write --allow-read --unstable write.ts`
-```js
+```typescript
+/**
+ * write.ts
+ */
import {
ensureFileSync,
writeJsonSync,
diff --git a/docs/examples/subprocess.md b/docs/examples/subprocess.md
index 72a3bc862..fad6c71bf 100644
--- a/docs/examples/subprocess.md
+++ b/docs/examples/subprocess.md
@@ -1,10 +1,25 @@
-## Run subprocess
+# Creating a subprocess
-[API Reference](https://doc.deno.land/https/github.com/denoland/deno/releases/latest/download/lib.deno.d.ts#Deno.run)
+## Concepts
-Example:
+- Deno is capable of spawning a subprocess via
+ [Deno.run](https://doc.deno.land/builtin/stable#Deno.run)
+- `--allow-run` permission is required to spawn a subprocess
+- Spawned subprocesses do not run in a security sandbox
+- Communicate with the subprocess via the
+ [stdin](https://doc.deno.land/builtin/stable#Deno.stdin),
+ [stdout](https://doc.deno.land/builtin/stable#Deno.stdout) and
+ [stderr](https://doc.deno.land/builtin/stable#Deno.stderr) streams
+
+## Simple example
+
+This example is the equivalent of running `'echo hello'` from the command line.
```ts
+/**
+ * subprocess_simple.ts
+ */
+
// create subprocess
const p = Deno.run({
cmd: ["echo", "hello"],
@@ -21,16 +36,22 @@ $ deno run --allow-run ./subprocess_simple.ts
hello
```
-Here a function is assigned to `window.onload`. This function is called after
-the main script is loaded. This is the same as
-[onload](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)
-of the browsers, and it can be used as the main entrypoint.
+## Security
+
+The `--allow-run` permission is required for creation of a subprocess. Be aware
+that subprocesses are not run in a Deno sandbox and therefore have the same
+permissions as if you were to run the command from the command line yourself.
+
+## Communicating with subprocesses
-By default when you use `Deno.run()` subprocess inherits `stdin`, `stdout` and
-`stderr` of parent process. If you want to communicate with started subprocess
-you can use `"piped"` option.
+By default when you use `Deno.run()` the subprocess inherits `stdin`, `stdout`
+and `stderr` of the parent process. If you want to communicate with started
+subprocess you can use `"piped"` option.
```ts
+/**
+ * subprocess.ts
+ */
const fileNames = Deno.args;
const p = Deno.run({
diff --git a/docs/examples/tcp_echo.md b/docs/examples/tcp_echo.md
index 99e8cbd04..ba70aa795 100644
--- a/docs/examples/tcp_echo.md
+++ b/docs/examples/tcp_echo.md
@@ -1,9 +1,21 @@
-## TCP echo server
+# TCP echo server
+
+## Concepts
+
+- Listening for TCP port connections with
+ [Deno.listen](https://doc.deno.land/builtin/stable#Deno.listen)
+- Use [Deno.copy](https://doc.deno.land/builtin/stable#Deno.copy) to take
+ inbound data and redirect it to be outbound data
+
+## Example
This is an example of a server which accepts connections on port 8080, and
returns to the client anything it sends.
```ts
+/**
+ * echo_server.ts
+ */
const listener = Deno.listen({ port: 8080 });
console.log("listening on 0.0.0.0:8080");
for await (const conn of listener) {
@@ -11,24 +23,16 @@ for await (const conn of listener) {
}
```
-When this program is started, it throws PermissionDenied error.
-
-```shell
-$ deno run https://deno.land/std@$STD_VERSION/examples/echo_server.ts
-error: Uncaught PermissionDenied: network access to "0.0.0.0:8080", run again with the --allow-net flag
-► $deno$/dispatch_json.ts:40:11
- at DenoError ($deno$/errors.ts:20:5)
- ...
-```
-
-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:
+Run with:
```shell
-deno run --allow-net https://deno.land/std@$STD_VERSION/examples/echo_server.ts
+deno run --allow-net echo_server.ts
```
-To test it, try sending data to it with netcat:
+To test it, try sending data to it with
+[netcat](https://en.wikipedia.org/wiki/Netcat) (Linux/MacOS only). Below
+`'hello world'` is sent over the connection, which is then echoed back to the
+user:
```shell
$ nc localhost 8080
@@ -36,6 +40,6 @@ hello world
hello world
```
-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 back,
-without further complexity.
+Like the [cat.ts example](./unix_cat.md), the `copy()` function here also does
+not make unnecessary memory copies. It receives a packet from the kernel and
+sends back, without further complexity.
diff --git a/docs/examples/testing_if_main.md b/docs/examples/testing_if_main.md
deleted file mode 100644
index 67be70339..000000000
--- a/docs/examples/testing_if_main.md
+++ /dev/null
@@ -1,10 +0,0 @@
-## Testing if current file is the main program
-
-To test if the current script has been executed as the main input to the program
-check `import.meta.main`.
-
-```ts
-if (import.meta.main) {
- console.log("main");
-}
-```
diff --git a/docs/examples/unix_cat.md b/docs/examples/unix_cat.md
index efec9e3fb..f93d9c94d 100644
--- a/docs/examples/unix_cat.md
+++ b/docs/examples/unix_cat.md
@@ -1,9 +1,26 @@
-## An implementation of the unix "cat" program
+# An implementation of the unix "cat" program
+
+## Concepts
+
+- Use the Deno runtime API to output the contents of a file to the console
+- [Deno.args](https://doc.deno.land/builtin/stable#Deno.args) accesses the
+ command line arguments
+- [Deno.open](https://doc.deno.land/builtin/stable#Deno.open) is used to get a
+ handle to a file
+- [Deno.copy](https://doc.deno.land/builtin/stable#Deno.copy) is used to
+ transfer data from the file to the output stream
+- Files should be closed when you are finished with them
+- Modules can be run directly from remote URLs
+
+## Example
In this program each command-line argument is assumed to be a filename, the file
-is opened, and printed to stdout.
+is opened, and printed to stdout (e.g. the console).
```ts
+/**
+ * cat.ts
+ */
for (let i = 0; i < Deno.args.length; i++) {
const filename = Deno.args[i];
const file = await Deno.open(filename);
@@ -12,12 +29,7 @@ for (let i = 0; i < Deno.args.length; i++) {
}
```
-The `copy()` function here actually makes no more than the necessary kernel ->
-userspace -> kernel copies. That is, the same memory from which data is read
-from the file, is written to stdout. This illustrates a general design goal for
-I/O streams in Deno.
-
-Try the program:
+To run the program:
```shell
deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd