diff options
author | Bartek Iwańczuk <biwanczuk@gmail.com> | 2021-07-20 16:25:36 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-07-20 16:25:36 +0200 |
commit | d744c0c6d9a557bbaa2a23571ffb3acabf19c35a (patch) | |
tree | 6f7fb8a71b786e79c48f4b2c11a5a9ca988717e8 /docs/examples | |
parent | 9b9becf1ae256b645e37a7eecf3441f3ae4b8ea5 (diff) |
chore: move docs to separate repository
Diffstat (limited to 'docs/examples')
-rw-r--r-- | docs/examples/fetch_data.md | 58 | ||||
-rw-r--r-- | docs/examples/file_server.md | 63 | ||||
-rw-r--r-- | docs/examples/file_system_events.md | 40 | ||||
-rw-r--r-- | docs/examples/hello_world.md | 79 | ||||
-rw-r--r-- | docs/examples/http_server.md | 88 | ||||
-rw-r--r-- | docs/examples/import_export.md | 120 | ||||
-rw-r--r-- | docs/examples/manage_dependencies.md | 73 | ||||
-rw-r--r-- | docs/examples/module_metadata.md | 68 | ||||
-rw-r--r-- | docs/examples/os_signals.md | 83 | ||||
-rw-r--r-- | docs/examples/read_write_files.md | 108 | ||||
-rw-r--r-- | docs/examples/subprocess.md | 99 | ||||
-rw-r--r-- | docs/examples/tcp_echo.md | 47 | ||||
-rw-r--r-- | docs/examples/unix_cat.md | 36 |
13 files changed, 0 insertions, 962 deletions
diff --git a/docs/examples/fetch_data.md b/docs/examples/fetch_data.md deleted file mode 100644 index 607225a2a..000000000 --- a/docs/examples/fetch_data.md +++ /dev/null @@ -1,58 +0,0 @@ -# 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 `fetch()` method. For -more information on fetch read the -[MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). - -The exception with Deno occurs when running a script which makes a call over the -web. Deno is secure by default which means access to IO (Input / Output) is -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 -/** - * Output: JSON Data - */ -const json = fetch("https://api.github.com/users/denoland"); - -json.then((response) => { - return response.json(); -}).then((jsonData) => { - console.log(jsonData); -}); - -/** - * Output: HTML Data - */ -const text = fetch("https://deno.land/"); - -text.then((response) => { - return response.text(); -}).then((textData) => { - console.log(textData); -}); - -/** - * Output: Error Message - */ -const error = fetch("https://does.not.exist/"); - -error.catch((error) => console.log(error.message)); -``` diff --git a/docs/examples/file_server.md b/docs/examples/file_server.md deleted file mode 100644 index 57a6d710a..000000000 --- a/docs/examples/file_server.md +++ /dev/null @@ -1,63 +0,0 @@ -# File server - -## 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 -``` - -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:4507/ -``` - -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 --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 deleted file mode 100644 index ba61d9284..000000000 --- a/docs/examples/file_system_events.md +++ /dev/null @@ -1,40 +0,0 @@ -# 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 -/** - * watcher.ts - */ -const watcher = Deno.watchFs("."); -for await (const event of watcher) { - console.log(">>>> event", event); - // 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](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 deleted file mode 100644 index cb45e5393..000000000 --- a/docs/examples/hello_world.md +++ /dev/null @@ -1,79 +0,0 @@ -# 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. - -## JavaScript - -In this JavaScript example the message `Hello [name]` is printed to the console -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); -} - -function hello(name) { - return "Hello " + capitalize(name); -} - -console.log(hello("john")); -console.log(hello("Sarah")); -console.log(hello("kai")); - -/** - * Output: - * - * Hello John - * Hello Sarah - * Hello Kai -**/ -``` - -## TypeScript - -This TypeScript example is exactly the same as the JavaScript example above, the -code just has the additional type information which TypeScript supports. - -The `deno run` command is exactly the same, it just references a `*.ts` file -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); -} - -function hello(name: string): string { - return "Hello " + capitalize(name); -} - -console.log(hello("john")); -console.log(hello("Sarah")); -console.log(hello("kai")); - -/** - * Output: - * - * Hello John - * Hello Sarah - * Hello Kai -**/ -``` diff --git a/docs/examples/http_server.md b/docs/examples/http_server.md deleted file mode 100644 index af239dfd3..000000000 --- a/docs/examples/http_server.md +++ /dev/null @@ -1,88 +0,0 @@ -# Simple HTTP web server - -## Concepts - -- Use Deno's integrated HTTP server 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. - -> ℹ️ The _native_ HTTP server is currently unstable, meaning the API is not -> finalized and may change in breaking ways in future version of Deno. To have -> the APIs discussed here available, you must run Deno with the `--unstable` -> flag. - -## Sample web server - -In this example, the user-agent of the client is returned to the client: - -**webserver.ts**: - -```ts -// Start listening on port 8080 of localhost. -const server = Deno.listen({ port: 8080 }); -console.log(`HTTP webserver running. Access it at: http://localhost:8080/`); - -// Connections to the server will be yielded up as an async iterable. -for await (const conn of server) { - // In order to not be blocking, we need to handle each connection individually - // in its own async function. - (async () => { - // This "upgrades" a network connection into an HTTP connection. - const httpConn = Deno.serveHttp(conn); - // Each request sent over the HTTP connection will be yielded as an async - // iterator from the HTTP connection. - for await (const requestEvent of httpConn) { - // The native HTTP server uses the web standard `Request` and `Response` - // objects. - const body = `Your user-agent is:\n\n${requestEvent.request.headers.get( - "user-agent", - ) ?? "Unknown"}`; - // The requestEvent's `.respondWith()` method is how we send the response - // back to the client. - requestEvent.respondWith( - new Response(body, { - status: 200, - }), - ); - } - })(); -} -``` - -Then run this with: - -```shell -deno run --allow-net --unstable webserver.ts -``` - -Then navigate to `http://localhost:8080/` in a browser. - -### Using the `std/http` library - -If you do not want to use the unstable APIs, you can still use the standard -library's HTTP server: - -**webserver.ts**: - -```ts -import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; - -const server = serve({ 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 }); -} -``` - -Then run this with: - -```shell -deno run --allow-net webserver.ts -``` diff --git a/docs/examples/import_export.md b/docs/examples/import_export.md deleted file mode 100644 index 7eaea31ba..000000000 --- a/docs/examples/import_export.md +++ /dev/null @@ -1,120 +0,0 @@ -# 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. - -It adopts browser-like module resolution, meaning that file names must be -specified in full. You may not omit the file extension and there is no special -handling of `index.js`. - -```js -import { add, multiply } from "./arithmetic.ts"; -``` - -Dependencies are also imported directly, there is no package management -overhead. Local modules are imported in exactly the same way as remote modules. -As the examples show below, the same functionality can be produced in the same -way with local or remote modules. - -## Local Import - -In this example the `add` and `multiply` functions are imported from a local -`arithmetic.ts` module. - -**Command:** `deno run local.ts` - -```ts -/** - * local.ts - */ -import { add, multiply } from "./arithmetic.ts"; - -function totalCost(outbound: number, inbound: number, tax: number): number { - return multiply(add(outbound, inbound), tax); -} - -console.log(totalCost(19, 31, 1.2)); -console.log(totalCost(45, 27, 1.15)); - -/** - * Output - * - * 60 - * 82.8 - */ -``` - -## Remote Import - -In the local import example above an `add` and `multiply` method are imported -from a locally stored arithmetic module. The same functionality can be created -by importing `add` and `multiply` methods from a remote module too. - -In this case the Ramda module is referenced, including the version number. Also -note a JavaScript module is imported directly into a TypeScript module, Deno has -no problem handling this. - -**Command:** `deno run ./remote.ts` - -```ts -/** - * remote.ts - */ -import { - add, - multiply, -} from "https://x.nest.land/ramda@0.27.0/source/index.js"; - -function totalCost(outbound: number, inbound: number, tax: number): number { - return multiply(add(outbound, inbound), tax); -} - -console.log(totalCost(19, 31, 1.2)); -console.log(totalCost(45, 27, 1.15)); - -/** - * Output - * - * 60 - * 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 deleted file mode 100644 index ed5df9710..000000000 --- a/docs/examples/manage_dependencies.md +++ /dev/null @@ -1,73 +0,0 @@ -# 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 -dependencies it will become cumbersome and time consuming to update modules if -they are all imported individually into individual modules. - -The standard practice for solving this problem in Deno is to create a `deps.ts` -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. If now for example -one remote dependency is used in several files, upgrading to a new version of -this remote dependency is much simpler as this can be done just within -`deps.ts`. - -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. - -## Example - -```ts -/** - * deps.ts - * - * This module re-exports the required methods from the dependant remote Ramda module. - **/ -export { - add, - multiply, -} from "https://x.nest.land/ramda@0.27.0/source/index.js"; -``` - -In this example the same functionality is created as is the case in the -[local and remote import examples](./import_export.md). But in this case instead -of the Ramda module being referenced directly it is referenced by proxy using a -local `deps.ts` module. - -**Command:** `deno run example.ts` - -```ts -/** - * example.ts - */ - -import { add, multiply } from "./deps.ts"; - -function totalCost(outbound: number, inbound: number, tax: number): number { - return multiply(add(outbound, inbound), tax); -} - -console.log(totalCost(19, 31, 1.2)); -console.log(totalCost(45, 27, 1.15)); - -/** - * Output - * - * 60 - * 82.8 - */ -``` diff --git a/docs/examples/module_metadata.md b/docs/examples/module_metadata.md deleted file mode 100644 index c58c82648..000000000 --- a/docs/examples/module_metadata.md +++ /dev/null @@ -1,68 +0,0 @@ -# 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 deleted file mode 100644 index e49c3eb76..000000000 --- a/docs/examples/os_signals.md +++ /dev/null @@ -1,83 +0,0 @@ -# Handle OS Signals - -> This program makes use of an unstable Deno feature. Learn more about -> [unstable features](../runtime/stability.md). - -## 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 deleted file mode 100644 index 8c1eae1ee..000000000 --- a/docs/examples/read_write_files.md +++ /dev/null @@ -1,108 +0,0 @@ -# Read and write files - -## 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). -- 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. Therefore when interacting -with the filesystem the `--allow-read` and `--allow-write` flags must be used -with the `deno run` command. - -## Reading a text file - -The Deno runtime API makes it possible to read text files via the -`Deno.readTextFile()` method, it just requires a path string or URL object. The -method returns a promise which provides access to the file's text data. - -**Command:** `deno run --allow-read read.ts` - -```typescript -/** - * read.ts - */ -const text = Deno.readTextFile("./people.json"); - -text.then((response) => console.log(response)); - -/** - * Output: - * - * [ - * {"id": 1, "name": "John", "age": 23}, - * {"id": 2, "name": "Sandra", "age": 51}, - * {"id": 5, "name": "Devika", "age": 11} - * ] - */ -``` - -## Writing a text file - -The Deno runtime API allows developers to write text to files via the -`Deno.writeTextFile()` method. It just requires a file path and text string. The -method returns a promise which resolves when the file was successfully written. - -To run the command the `--allow-write` flag must be supplied to the `deno run` -command. - -**Command:** `deno run --allow-write write.ts` - -```typescript -/** - * write.ts - */ -const write = Deno.writeTextFile("./hello.txt", "Hello World!"); - -write.then(() => console.log("File written to ./hello.txt")); - -/** - * Output: File written to ./hello.txt - */ -``` - -By combining `Deno.writeTextFile` and `JSON.stringify` you can easily write -serialized JSON objects to a file. This example uses synchronous -`Deno.writeTextFileSync`, but this can also be done asynchronously using -`await Deno.writeTextFile`. - -To execute the code the `deno run` command needs the write flag. - -**Command:** `deno run --allow-write write.ts` - -```typescript -/** - * write.ts - */ -function writeJson(path: string, data: object): string { - try { - Deno.writeTextFileSync(path, JSON.stringify(data)); - - return "Written to " + path; - } catch (e) { - return e.message; - } -} - -console.log(writeJson("./data.json", { hello: "World" })); - -/** - * Output: Written to ./data.json - */ -``` diff --git a/docs/examples/subprocess.md b/docs/examples/subprocess.md deleted file mode 100644 index e5956e1af..000000000 --- a/docs/examples/subprocess.md +++ /dev/null @@ -1,99 +0,0 @@ -# Creating a subprocess - -## Concepts - -- 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. -- Use a specific shell by providing its path/name and its string input switch, - e.g. `Deno.run({cmd: ["bash", "-c", '"ls -la"']});` - -## 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"], -}); - -// await its completion -await p.status(); -``` - -Run it: - -```shell -$ deno run --allow-run ./subprocess_simple.ts -hello -``` - -## 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()` 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({ - cmd: [ - "deno", - "run", - "--allow-read", - "https://deno.land/std@$STD_VERSION/examples/cat.ts", - ...fileNames, - ], - stdout: "piped", - stderr: "piped", -}); - -const { code } = await p.status(); - -// Reading the outputs closes their pipes -const rawOutput = await p.output(); -const rawError = await p.stderrOutput(); - -if (code === 0) { - await Deno.stdout.write(rawOutput); -} else { - const errorString = new TextDecoder().decode(rawError); - console.log(errorString); -} - -Deno.exit(code); -``` - -When you run it: - -```shell -$ deno run --allow-run ./subprocess.ts <somefile> -[file content] - -$ deno run --allow-run ./subprocess.ts non_existent_file.md - -Uncaught NotFound: No such file or directory (os error 2) - at DenoError (deno/js/errors.ts:22:5) - at maybeError (deno/js/errors.ts:41:12) - at handleAsyncMsgFromRust (deno/js/dispatch.ts:27:17) -``` diff --git a/docs/examples/tcp_echo.md b/docs/examples/tcp_echo.md deleted file mode 100644 index f016b8bd8..000000000 --- a/docs/examples/tcp_echo.md +++ /dev/null @@ -1,47 +0,0 @@ -# TCP echo server - -## Concepts - -- Listening for TCP port connections with - [Deno.listen](https://doc.deno.land/builtin/stable#Deno.listen). -- Use - [copy](https://doc.deno.land/https/deno.land/std@$STD_VERSION/io/util.ts#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 - */ -import { copy } from "https://deno.land/std@$STD_VERSION/io/util.ts"; -const listener = Deno.listen({ port: 8080 }); -console.log("listening on 0.0.0.0:8080"); -for await (const conn of listener) { - copy(conn, conn).finally(() => conn.close()); -} -``` - -Run with: - -```shell -deno run --allow-net echo_server.ts -``` - -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 -hello world -hello world -``` - -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/unix_cat.md b/docs/examples/unix_cat.md deleted file mode 100644 index 0ce28d718..000000000 --- a/docs/examples/unix_cat.md +++ /dev/null @@ -1,36 +0,0 @@ -# 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. -- [copy](https://doc.deno.land/https/deno.land/std@$STD_VERSION/io/util.ts#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 (e.g. the console). - -```ts -/** - * cat.ts - */ -import { copy } from "https://deno.land/std@$STD_VERSION/io/util.ts"; -for (const filename of Deno.args) { - const file = await Deno.open(filename); - await copy(file, Deno.stdout); - file.close(); -} -``` - -To run the program: - -```shell -deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd -``` |