├── .github ├── .mlc_config.json ├── dependabot.yml ├── import_map.json └── workflows │ ├── check-links.yml │ ├── ci.yml │ ├── main.yml │ ├── suggest-format.yml │ └── update-algolia.yml ├── .gitignore ├── .tools ├── .env.example ├── deno.json ├── import-map.json └── main.ts ├── LICENSE ├── README.md ├── advanced.md ├── advanced ├── continuous_integration.md ├── deploying_deno.md ├── deploying_deno │ ├── aws_lightsail.md │ ├── cloudflare_workers.md │ ├── digital_ocean.md │ ├── google_cloud_run.md │ └── kinsta.md ├── embedding_deno.md ├── jsx_dom.md ├── jsx_dom │ ├── css.md │ ├── deno_dom.md │ ├── jsdom.md │ ├── jsx.md │ ├── linkedom.md │ ├── overview.md │ └── twind.md ├── language_server.md ├── language_server │ ├── imports.md │ ├── overview.md │ └── testing_api.md ├── publishing.md ├── publishing │ └── dnt.md ├── typescript.md └── typescript │ ├── configuration.md │ ├── faqs.md │ ├── migration.md │ ├── overview.md │ └── types.md ├── basics.md ├── basics ├── connecting_to_databases.md ├── debugging_your_code.md ├── env_variables.md ├── import_maps.md ├── modules.md ├── modules │ ├── integrity_checking.md │ ├── private.md │ ├── proxies.md │ └── reloading_modules.md ├── permissions.md ├── react.md ├── standard_library.md ├── testing.md └── testing │ ├── assertions.md │ ├── behavior_driven_development.md │ ├── coverage.md │ ├── documentation.md │ ├── mocking.md │ ├── sanitizers.md │ └── snapshot_testing.md ├── examples.md ├── examples ├── chat_app.md ├── fetch_data.md ├── file_server.md ├── file_system_events.md ├── hashbang.md ├── hello_world.md ├── http_server.md ├── manage_dependencies.md ├── module_metadata.md ├── os_signals.md ├── read_write_files.md ├── subprocess.md ├── tcp_echo.md ├── tcp_server.md ├── unix_cat.md └── word_finder.md ├── getting_started.md ├── getting_started ├── command_line_interface.md ├── configuration_file.md ├── first_steps.md ├── installation.md ├── setup_your_environment.md ├── typescript.md └── web_frameworks.md ├── help.md ├── images ├── chat_app_render.png ├── debugger1.jpg ├── debugger2.jpg ├── debugger3.jpg ├── debugger4.jpg ├── debugger5.jpg ├── debugger7.jpg ├── deno3.png ├── how-to │ ├── aws-lightsail │ │ ├── create-container-service-on-aws.png │ │ ├── hello-world-from-deno-and-aws-lightsail.png │ │ ├── hello-world-from-localhost.png │ │ └── new-image-on-docker-hub.png │ ├── cloudflare-workers │ │ └── main-on-cloudflare.png │ ├── digital-ocean │ │ ├── hello-from-deno-and-digital-ocean.png │ │ ├── hello-world-from-localhost.png │ │ └── new-deno-image-on-digital-ocean-container-registry.png │ ├── google-cloud-run │ │ ├── hello-from-google-cloud-run.png │ │ ├── hello-world-from-localhost.png │ │ ├── image-in-google-artifact-registry.png │ │ └── new-repository-in-google-artifact-repository.png │ ├── prisma │ │ ├── 1-dinosaurs-in-prisma.png │ │ ├── 2-dinosaurs-from-api.png │ │ └── 3-new-dinosaur-in-prisma.png │ ├── react │ │ ├── dinosaur-api.png │ │ └── react-dinosaur-app-demo.gif │ ├── redis │ │ ├── cached-redis-body.png │ │ ├── cached-redis-header.png │ │ ├── uncached-redis-body.png │ │ └── uncached-redis-header.png │ └── vue │ │ ├── api-response.png │ │ ├── default-vue-app.png │ │ └── vue-demo.gif ├── jb-ide-debug.png ├── node_modules_dir.png ├── private-github-new-token.png ├── private-github-token-display.png ├── private-pat.png ├── word_finder.png └── workspace_folder_config.png ├── introduction.md ├── node.md ├── node ├── cdns.md ├── compatibility.md ├── faqs.md ├── how_to_with_npm.md ├── how_to_with_npm │ ├── apollo.md │ ├── express.md │ ├── mongoose.md │ ├── mysql2.md │ ├── planetscale.md │ ├── prisma.md │ ├── react.md │ ├── redis.md │ └── vue.md ├── migrate.md ├── node_specifiers.md ├── npm_specifiers.md └── package_json.md ├── references.md ├── references ├── cheatsheet.md ├── contributing.md ├── contributing │ ├── architecture.md │ ├── building_from_source.md │ ├── profiling.md │ ├── release_schedule.md │ ├── style_guide.md │ └── web_platform_tests.md ├── vscode_deno.md └── vscode_deno │ └── testing_api.md ├── runtime.md ├── runtime ├── builtin_apis.md ├── ffi_api.md ├── http_server_apis.md ├── import_meta_api.md ├── kv.md ├── kv │ ├── key_expiration.md │ ├── key_space.md │ ├── operations.md │ ├── secondary_indexes.md │ └── transactions.md ├── location_api.md ├── permission_apis.md ├── program_lifecycle.md ├── stability.md ├── web_platform_apis.md ├── web_storage_api.md ├── webassembly.md ├── webassembly │ ├── using_streaming_wasm.md │ ├── using_wasm.md │ └── wasm_resources.md └── workers.md ├── toc.json ├── tools.md ├── tools ├── benchmarker.md ├── bundler.md ├── compiler.md ├── dependency_inspector.md ├── documentation_generator.md ├── formatter.md ├── init.md ├── linter.md ├── repl.md ├── script_installer.md ├── task_runner.md └── vendor.md └── typos.toml /.github/.mlc_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "ignorePatterns": [ 3 | { 4 | "pattern": [ 5 | "^https://deno.land/(std|api)@" 6 | ] 7 | }, 8 | { 9 | "pattern": [ 10 | "^https://github.com/denoland/deno/blob/" 11 | ] 12 | }, 13 | { 14 | "pattern": [ 15 | "^https://deno.land/images/schematic_v0.2.png" 16 | ] 17 | }, 18 | { 19 | "pattern": [ 20 | "^https://kinsta.com/signup/" 21 | ] 22 | }, 23 | { 24 | "pattern": [ 25 | "^http://(localhost|0.0.0.0)" 26 | ] 27 | }, 28 | { 29 | "pattern": [ 30 | "^/api" 31 | ] 32 | }, 33 | { 34 | "pattern": [ 35 | "^https://dash.cloudflare.com" 36 | ] 37 | }, 38 | { 39 | "pattern": [ 40 | "^https://web.pulsar-edit.dev/" 41 | ] 42 | } 43 | ], 44 | "httpHeaders": [ 45 | { 46 | "urls": ["https://crates.io"], 47 | "headers": { 48 | "accept": "text/html" 49 | } 50 | }, 51 | { 52 | "urls": ["https://deno.land"], 53 | "headers": { 54 | "accept": "text/html" 55 | } 56 | } 57 | ] 58 | } 59 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | # Check for updates to GitHub Actions every week 8 | interval: "weekly" 9 | -------------------------------------------------------------------------------- /.github/import_map.json: -------------------------------------------------------------------------------- 1 | { 2 | "imports": { 3 | "https://deno.land/std@$STD_VERSION/": "https://deno.land/std/", 4 | "https://deno.land/x/mongo@LATEST_VERSION/": "https://deno.land/x/mongo/", 5 | "jsdom": "https://esm.sh/jsdom" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.github/workflows/check-links.yml: -------------------------------------------------------------------------------- 1 | name: check-links 2 | 3 | on: 4 | push: 5 | branches: main 6 | pull_request: 7 | branches: main 8 | schedule: 9 | - cron: '0 0 * * *' # every day at midnight 10 | jobs: 11 | broken-links: 12 | runs-on: ubuntu-22.04 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Check Markdown Links 16 | uses: ruzickap/action-my-markdown-link-checker@v1 17 | with: 18 | config_file: .github/.mlc_config.json 19 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | typos: 11 | name: spell-check 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Checkout repository 15 | uses: actions/checkout@v4 16 | 17 | - uses: crate-ci/typos@master 18 | with: 19 | config: ./typos.toml 20 | 21 | format: 22 | runs-on: ubuntu-latest 23 | steps: 24 | - name: Checkout repository 25 | uses: actions/checkout@v4 26 | 27 | - name: Set up Deno 28 | uses: denoland/setup-deno@v1 29 | 30 | - name: Format 31 | run: deno fmt --check 32 | 33 | type-check: 34 | runs-on: ubuntu-latest 35 | steps: 36 | - name: Checkout repository 37 | uses: actions/checkout@v4 38 | 39 | - name: Set up Deno 40 | uses: denoland/setup-deno@v1 41 | 42 | - name: Type-check Deno manual 43 | run: deno test --doc --unstable --import-map=.github/import_map.json --no-check=remote 44 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: main 2 | on: 3 | workflow_run: 4 | types: 5 | - requested 6 | workflows: 7 | - ci 8 | 9 | jobs: 10 | post_status_check: 11 | name: Post PR preview status 12 | runs-on: ubuntu-22.04 13 | steps: 14 | - name: Create status item 15 | uses: Sibz/github-status-action@v1 16 | with: 17 | authToken: ${{ github.token }} 18 | sha: ${{ github.event.workflow_run.head_sha }} 19 | context: PR preview 20 | state: success 21 | target_url: https://deno.land/manual@${{ github.event.workflow_run.head_sha }} 22 | - name: Create deployment 23 | uses: chrnorm/deployment-action@releases/v1 24 | with: 25 | token: "${{ github.token }}" 26 | ref: ${{ github.event.workflow_run.head_sha }} 27 | environment: preview 28 | initial_status: success 29 | target_url: https://deno.land/manual@${{ github.event.workflow_run.head_sha }} 30 | description: PR preview -------------------------------------------------------------------------------- /.github/workflows/suggest-format.yml: -------------------------------------------------------------------------------- 1 | name: suggest-format 2 | 3 | on: 4 | pull_request: 5 | branches: [main] 6 | 7 | jobs: 8 | suggest-format: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout repository 12 | uses: actions/checkout@v4 13 | 14 | - name: Set up Deno 15 | uses: denoland/setup-deno@v1 16 | 17 | - name: Format 18 | run: deno fmt 19 | 20 | - name: Create Suggestion 21 | uses: reviewdog/action-suggester@v1 22 | with: 23 | tool_name: deno fmt 24 | -------------------------------------------------------------------------------- /.github/workflows/update-algolia.yml: -------------------------------------------------------------------------------- 1 | name: main 2 | on: 3 | push: 4 | tags: 5 | - '*' 6 | 7 | jobs: 8 | update-algolia: 9 | runs-on: ubuntu-latest 10 | env: 11 | ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} 12 | ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }} 13 | 14 | steps: 15 | - name: Checkout repository 16 | uses: actions/checkout@v4 17 | 18 | - name: Set up Deno 19 | uses: denoland/setup-deno@v1 20 | 21 | - name: Update Algolia 22 | working-directory: ./.tools 23 | run: deno task update 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .env 3 | .vscode -------------------------------------------------------------------------------- /.tools/.env.example: -------------------------------------------------------------------------------- 1 | # Algolia Credentials 2 | ALGOLIA_APP_ID=client_id 3 | ALGOLIA_API_KEY=api_key 4 | -------------------------------------------------------------------------------- /.tools/deno.json: -------------------------------------------------------------------------------- 1 | { 2 | "importMap": "./import-map.json", 3 | "tasks": { 4 | "update": "deno run --check --allow-read=.. --allow-env --allow-net main.ts" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.tools/import-map.json: -------------------------------------------------------------------------------- 1 | { 2 | "imports": { 3 | "@algolia/requester-fetch": "https://esm.sh/@algolia/requester-fetch@4.14.3", 4 | "algoliasearch": "https://esm.sh/algoliasearch@4.14.3", 5 | "dax": "https://deno.land/x/dax@0.11.0/mod.ts", 6 | "markdown_records": "https://deno.land/x/markdown_records@0.2.0/mod.ts", 7 | "std/": "https://deno.land/std@0.178.0/" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.tools/main.ts: -------------------------------------------------------------------------------- 1 | import { createFetchRequester } from "@algolia/requester-fetch"; 2 | import algoliasearch from "algoliasearch"; 3 | import dax from "dax"; 4 | import { MarkdownRecord, toRecords } from "markdown_records"; 5 | import { load } from "std/dotenv/mod.ts"; 6 | import toc from "../toc.json" assert { type: "json" }; 7 | 8 | export interface TableOfContents { 9 | [slug: string]: { 10 | name: string; 11 | children?: TableOfContents; 12 | } | string; 13 | } 14 | 15 | const MANUAL_INDEX = "manual"; 16 | 17 | dax.logStep("Generate manual search records..."); 18 | 19 | dax.logStep("Parsing manual toc..."); 20 | 21 | dax.logLight(` ${Object.keys(toc).length} sections in toc.`); 22 | 23 | interface SearchRecordHierarchy { 24 | [lvl: string]: string | null; 25 | } 26 | 27 | type SearchRecord = Omit & { 28 | objectID: string; 29 | docPath: string; 30 | level: number; 31 | hierarchy: SearchRecordHierarchy; 32 | }; 33 | 34 | function mergeHierarchy( 35 | docHierarchy: string[], 36 | recordHierarchy: string[], 37 | ): [SearchRecordHierarchy, number] { 38 | const entries: [string, string | null][] = []; 39 | let count = 0; 40 | for (const item of docHierarchy) { 41 | entries.push([`lvl${count++}`, item]); 42 | } 43 | if ( 44 | docHierarchy[docHierarchy.length - 1].toLowerCase() === 45 | recordHierarchy[0]?.toLowerCase() 46 | ) { 47 | recordHierarchy.shift(); 48 | } 49 | for (const item of recordHierarchy) { 50 | entries.push([`lvl${count++}`, item]); 51 | } 52 | const level = count; 53 | while (count < 7) { 54 | entries.push([`lvl${count++}`, null]); 55 | } 56 | return [Object.fromEntries(entries) as SearchRecordHierarchy, level]; 57 | } 58 | 59 | function markdownToSearch( 60 | docHierarchy: string[], 61 | docPath: string, 62 | { hierarchy: recordHierarchy, ...record }: MarkdownRecord, 63 | idx: number, 64 | ): SearchRecord { 65 | const objectID = `${docPath}-${idx}`; 66 | const [hierarchy, level] = mergeHierarchy(docHierarchy, recordHierarchy); 67 | return { 68 | objectID, 69 | level, 70 | docPath, 71 | hierarchy, 72 | ...record, 73 | }; 74 | } 75 | 76 | let searchRecords: SearchRecord[] = []; 77 | 78 | async function travelToC( 79 | table: TableOfContents, 80 | parents: [name: string, id: string][], 81 | ) { 82 | for (const [id, section] of Object.entries(table)) { 83 | const name = typeof section === "string" ? section : section.name; 84 | const fullHierachy: [string, string][] = [...parents, [name, id]]; 85 | let content: string; 86 | const fullId = fullHierachy.map(([_, id]) => id).join("/"); 87 | try { 88 | content = await Deno.readTextFile(`../${fullId}.md`); 89 | } catch (err) { 90 | dax.logError(`Error attempting to read "/${fullId}.md".`); 91 | console.log(parents, fullId, section, err); 92 | continue; 93 | } 94 | const docPath = `/manual/${fullId}`; 95 | const nameHierarchy = fullHierachy.map(([name, _]) => name); 96 | dax.logLight(` generating "${docPath}"...`); 97 | const records = (await toRecords(content)) 98 | .map((record, i) => markdownToSearch(nameHierarchy, docPath, record, i)); 99 | searchRecords = searchRecords.concat(records); 100 | 101 | if (typeof section !== "string" && section.children) { 102 | await travelToC(section.children, fullHierachy); 103 | } 104 | } 105 | } 106 | 107 | await travelToC(toc, []); 108 | dax.logStep(`Uploading ${searchRecords.length} search records to algolia...`); 109 | 110 | await load({ export: true }); 111 | const appId = Deno.env.get("ALGOLIA_APP_ID") ?? ""; 112 | const apiKey = Deno.env.get("ALGOLIA_API_KEY") ?? ""; 113 | const requester = createFetchRequester(); 114 | const app = algoliasearch(appId, apiKey, { requester }); 115 | 116 | dax.logLight(` deleting objects from "${MANUAL_INDEX}"...`); 117 | const manualIndex = app.initIndex(MANUAL_INDEX); 118 | await manualIndex.clearObjects(); 119 | 120 | dax.logLight(` uploading objects to "${MANUAL_INDEX}"...`); 121 | const response = await app.multipleBatch( 122 | searchRecords.map((body) => ({ 123 | indexName: MANUAL_INDEX, 124 | action: "addObject", 125 | body, 126 | })), 127 | ); 128 | 129 | dax.logLight(` uploaded ${response.objectIDs.length}.`); 130 | 131 | dax.logStep("Done."); 132 | // algolia holds open things for some reason... 133 | Deno.exit(0); 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018-2022 the Deno authors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # (DEPRECATED) Deno Manual 2 | 3 | This repository was formerly the home of the Deno manual, running at 4 | deno.land/manual. The instructions below describe how to run the doc site and 5 | preview changes. 6 | 7 | **New contributions should be made to 8 | [docs.deno.com](https://github.com/denoland/deno-docs)** 9 | -------------------------------------------------------------------------------- /advanced.md: -------------------------------------------------------------------------------- 1 | # Advanced 2 | 3 | In this chapter, you will find advanced Deno concepts, including: 4 | 5 | - [Publishing Modules](./advanced/publishing.md) 6 | - [Embedding Deno](./advanced/embedding_deno.md) 7 | - [Language Server](./advanced/language_server.md) 8 | - [Continuous Integration](./advanced/continuous_integration.md) 9 | - [Using TypeScript](./advanced/typescript.md) 10 | - [Details on Using JSX and the DOM](./advanced/jsx_dom.md) 11 | -------------------------------------------------------------------------------- /advanced/deploying_deno.md: -------------------------------------------------------------------------------- 1 | # Deploying Deno 2 | 3 | Often times, we don't want to maintain hardware for our Deno scripts or apps to 4 | run. This section describes various ways to deploy Deno into the cloud. 5 | 6 | Though the easiest and fastest way to deploy Deno is with 7 | [Deno Deploy](https://deno.com/deploy), you can deploy Deno into any virtual 8 | private server. 9 | 10 | This section contains How To guides on how to deploy Deno to different 11 | platforms. 12 | 13 | - [Digital Ocean](deploying_deno/digital_ocean.md) 14 | - [AWS Lightsail](deploying_deno/aws_lightsail.md) 15 | - [Google Cloud Run](deploying_deno/google_cloud_run.md) 16 | - [Cloudflare Workers](deploying_deno/cloudflare_workers.md) 17 | - [Kinsta](deploying_deno/kinsta.md) 18 | -------------------------------------------------------------------------------- /advanced/deploying_deno/cloudflare_workers.md: -------------------------------------------------------------------------------- 1 | # Deploying Deno to Cloudflare Workers 2 | 3 | Cloudflare Workers allows you to run JavaScript on Cloudflare's edge network. 4 | 5 | This is a short How To guide on deploying a Deno function to Cloudflare Workers. 6 | 7 | Note: You would only be able to deploy 8 | [Module Workers](https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/) 9 | instead of web servers or apps. 10 | 11 | ## Setup `denoflare` 12 | 13 | In order to deploy Deno to Cloudflare, we'll use this community created CLI 14 | [`denoflare`](https://denoflare.dev/). 15 | 16 | [Install it](https://denoflare.dev/cli/#installation): 17 | 18 | ```shell, ignore 19 | deno install --unstable --allow-read --allow-net --allow-env --allow-run --name denoflare --force \ 20 | https://raw.githubusercontent.com/skymethod/denoflare/v0.5.11/cli/cli.ts 21 | ``` 22 | 23 | ## Create your function 24 | 25 | In a new directory, let's create a `main.ts` file, which will contain our Module 26 | Worker function: 27 | 28 | ```ts, ignore 29 | export default { 30 | fetch(request: Request): Response { 31 | return new Response("Hello, world!"); 32 | }, 33 | }; 34 | ``` 35 | 36 | At the very minimum, a Module Worker function must `export default` an object 37 | that exposes a `fetch` function, which returns a `Response` object. 38 | 39 | You can test this locally by running: 40 | 41 | ```shell, ignore 42 | denoflare serve main.ts 43 | ``` 44 | 45 | If you go to `localhost:8080` in your browser, you'll see the response will say: 46 | 47 | ``` 48 | Hello, world! 49 | ``` 50 | 51 | ## Configure `.denoflare` 52 | 53 | The next step is to create a `.denoflare` config file. In it, let's add: 54 | 55 | ```json 56 | { 57 | "$schema": "https://raw.githubusercontent.com/skymethod/denoflare/v0.5.11/common/config.schema.json", 58 | "scripts": { 59 | "main": { 60 | "path": "/absolute/path/to/main.ts", 61 | "localPort": 8000 62 | } 63 | }, 64 | "profiles": { 65 | "myprofile": { 66 | "accountId": "abcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 67 | "apiToken": "abcxxxxxxxxx_-yyyyyyyyyyyy-11-dddddddd" 68 | } 69 | } 70 | } 71 | ``` 72 | 73 | You can find your `accountId` by going to your 74 | [Cloudflare dashboard](https://dash.cloudflare.com/), clicking "Workers", and 75 | finding "Account ID" on the right side. 76 | 77 | You can generate an `apiToken` from your 78 | [Cloudflare API Tokens settings](https://dash.cloudflare.com/profile/api-tokens). 79 | When you create an API token, be sure to use the template "Edit Cloudflare 80 | Workers". 81 | 82 | After you add both to your `.denoflare` config, let's try pushing it to 83 | Cloudflare: 84 | 85 | ``` 86 | denoflare push main 87 | ``` 88 | 89 | Next, you can view your new function in your Cloudflare account: 90 | 91 | ![New function on Cloudflare Workers](../../images/how-to/cloudflare-workers/main-on-cloudflare.png) 92 | 93 | Boom! 94 | -------------------------------------------------------------------------------- /advanced/deploying_deno/kinsta.md: -------------------------------------------------------------------------------- 1 | # How to Deploy Deno on Kinsta 2 | 3 | [Kinsta Application Hosting](https://kinsta.com/application-hosting) is a 4 | service that lets you build and deploy your web apps directly from your Git 5 | repository. 6 | 7 | ## Preparing your application 8 | 9 | At **Kinsta**, we recommend using the 10 | [`deno-bin`](https://www.npmjs.com/package/deno-bin) package to run Deno 11 | applications. 12 | 13 | To do so, your `package.json` should look like this: 14 | 15 | ```json 16 | { 17 | "name": "deno app", 18 | "scripts": { 19 | "start": "deno run --allow-net index.js --port=${PORT}" 20 | }, 21 | "devDependencies": { 22 | "deno-bin": "^1.28.2" 23 | } 24 | } 25 | ``` 26 | 27 | ## Example application 28 | 29 | ```js 30 | import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; 31 | import { parse } from "https://deno.land/std@$STD_VERSION/flags/mod.ts"; 32 | 33 | const { args } = Deno; 34 | const argPort = parse(args).port ? Number(parse(args).port) : 8000; 35 | 36 | serve((_req) => new Response("Hello, world"), { port: argPort }); 37 | ``` 38 | 39 | The application itself is self-explanatory. It's crucial not to hardcode the 40 | `PORT` but use the environmental variable **Kinsta** provides. 41 | 42 | There is also a [repository](https://github.com/kinsta/hello-world-deno) that 43 | should help you to get started. 44 | 45 | ## Deployment 46 | 47 | 1. Register on 48 | [Kinsta Application Hosting](https://kinsta.com/signup/?product_type=app-db) 49 | or login directly to [My Kinsta](https://my.kinsta.com/) admin panel. 50 | 2. Go to the Applications tab. 51 | 3. Connect your GitHub repository. 52 | 4. Press the **Add service > Application button**. 53 | 5. Follow the wizard steps. 54 | -------------------------------------------------------------------------------- /advanced/embedding_deno.md: -------------------------------------------------------------------------------- 1 | # Embedding Deno 2 | 3 | Deno consists of multiple parts, one of which is `deno_core`. This is a Rust 4 | crate that can be used to embed a JavaScript runtime into your Rust application. 5 | Deno is built on top of `deno_core`. 6 | 7 | The Deno crate is hosted on [crates.io](https://crates.io/crates/deno_core). 8 | 9 | You can view the API on [docs.rs](https://docs.rs/deno_core). 10 | 11 | 12 | -------------------------------------------------------------------------------- /advanced/jsx_dom.md: -------------------------------------------------------------------------------- 1 | # Using JSX and the DOM 2 | 3 | This chapter covers more configuration details about using JSX and the DOM in 4 | Deno, including: 5 | 6 | - [Overview of JSX and the DOM in Deno](./jsx_dom/overview.md) 7 | - [Configuring JSX in Deno](./jsx_dom/jsx.md) 8 | - [Using LinkeDOM with Deno](./jsx_dom/linkedom.md) 9 | - [Using deno-dom with Deno](./jsx_dom/deno_dom.md) 10 | - [Using JSDOM with Deno](./jsx_dom/jsdom.md) 11 | - [Parsing and Stringifying CSS](./jsx_dom/css.md) 12 | - [Using Twind with Deno](./jsx_dom/twind.md) 13 | -------------------------------------------------------------------------------- /advanced/jsx_dom/css.md: -------------------------------------------------------------------------------- 1 | # Parsing and Stringifying CSS 2 | 3 | If you want to parse CSS to a abstract syntax tree (AST) then there are two 4 | solutions you might want to consider: 5 | 6 | - [reworkcss/css](https://github.com/reworkcss/css) 7 | - [deno_css](https://deno.land/x/css) 8 | 9 | `reworkcss/css` was written originally for Node.js but work well when consumed 10 | from a CDN. Importing from `esm.sh` also automatically combines the type 11 | definitions from DefinitelyTyped. It should be noted though that types on 12 | DefinitelyTyped are not _very good_ as many union types that should be tagged 13 | union types are just union types which leave the types very ambiguous and 14 | require a lot of type casting. 15 | 16 | Also, if you want to take an AST and generate CSS, `reworkcss/css` also provides 17 | capability to stringify the AST it generates. 18 | 19 | `deno_css` is authored in TypeScript specifically for Deno and is available on 20 | `deno.land/x`. 21 | 22 | ## Basic example with `reworkcss/css` 23 | 24 | In this example, we will parse some CSS into an AST and make a modification to 25 | the `background` declaration of the `body` rule, to change the color to `white`. 26 | Then we will stringify the modified CSS AST and output it to the console: 27 | 28 | ```ts, ignore 29 | import * as css from "https://esm.sh/css@3.0.0"; 30 | import { assert } from "https://deno.land/std@$STD_VERSION/assert/mod.ts"; 31 | 32 | declare global { 33 | interface AbortSignal { 34 | reason: unknown; 35 | } 36 | } 37 | 38 | const ast = css.parse(` 39 | body { 40 | background: #eee; 41 | color: #888; 42 | } 43 | `); 44 | 45 | assert(ast.stylesheet); 46 | const body = ast.stylesheet.rules[0] as css.Rule; 47 | assert(body.declarations); 48 | const background = body.declarations[0] as css.Declaration; 49 | background.value = "white"; 50 | 51 | console.log(css.stringify(ast)); 52 | ``` 53 | 54 | ## A basic example with `deno_css` 55 | 56 | In this example, we will parse some CSS into an AST and log out the `background` 57 | declaration of the `body` rule to the console. 58 | 59 | ```ts 60 | import * as css from "https://deno.land/x/css@0.3.0/mod.ts"; 61 | 62 | const ast = css.parse(` 63 | body { 64 | background: #eee; 65 | color: #888; 66 | } 67 | `); 68 | 69 | const [body] = ast.stylesheet.rules; 70 | const [background] = body.declarations; 71 | 72 | console.log(JSON.stringify(background, undefined, " ")); 73 | ``` 74 | -------------------------------------------------------------------------------- /advanced/jsx_dom/deno_dom.md: -------------------------------------------------------------------------------- 1 | # Using deno-dom with Deno 2 | 3 | [deno-dom](https://deno.land/x/deno_dom) is an implementation of DOM and HTML 4 | parser in Deno. It is implemented in Rust (via Wasm) and TypeScript. There is 5 | also a "native" implementation, leveraging the FFI interface. 6 | 7 | deno-dom aims for specification compliance, like jsdom and unlike LinkeDOM. 8 | Currently, deno-dom is slower than LinkeDOM for things like parsing data 9 | structures, but faster at some manipulation operations. Both deno-dom and 10 | LinkeDOM are significantly faster than jsdom. 11 | 12 | As of deno_dom v0.1.22-alpha supports running on Deno Deploy. So if you want 13 | strict standards alignment, consider using deno-dom over LinkeDOM. 14 | 15 | ## Basic example 16 | 17 | This example will take a test string and parse it as HTML and generate a DOM 18 | structure based on it. It will then query that DOM structure, picking out the 19 | first heading it encounters and print out the text content of that heading: 20 | 21 | ```ts 22 | import { DOMParser } from "https://deno.land/x/deno_dom/deno-dom-wasm.ts"; 23 | import { assert } from "https://deno.land/std@$STD_VERSION/assert/mod.ts"; 24 | 25 | const document = new DOMParser().parseFromString( 26 | ` 27 | 28 | 29 | Hello from Deno 30 | 31 | 32 |

Hello from Deno

33 |
34 | 35 | 38 |
39 | 40 | `, 41 | "text/html", 42 | ); 43 | 44 | assert(document); 45 | const h1 = document.querySelector("h1"); 46 | assert(h1); 47 | 48 | console.log(h1.textContent); 49 | ``` 50 | 51 | > Note: the example uses an unpinned version from `deno_land/x`, which you 52 | > likely don't want to do, because the version can change and cause unexpected 53 | > outcomes. You should use the latest version of available of 54 | > [deno-dom](https://deno.land/x/deno_dom). 55 | 56 | ## Faster startup 57 | 58 | Just importing the `deno-dom-wasm.ts` file bootstraps the Wasm code via top 59 | level await. The problem is that top level await blocks the module loading 60 | process. Especially with big Wasm projects, it is a lot more performant to 61 | initialize the Wasm after module loading is complete. 62 | 63 | _deno-dom_ has the solution for that, they provide an alternative version of the 64 | library that does not automatically init the Wasm, and requires you to do it in 65 | the code: 66 | 67 | ```ts 68 | import { 69 | DOMParser, 70 | initParser, 71 | } from "https://deno.land/x/deno_dom/deno-dom-wasm-noinit.ts"; 72 | 73 | (async () => { 74 | // initialize when you need it, but not at the top level 75 | await initParser(); 76 | 77 | const doc = new DOMParser().parseFromString( 78 | `

Lorem ipsum dolor...

`, 79 | "text/html", 80 | ); 81 | })(); 82 | ``` 83 | 84 | In addition, using the `deno-dom-native.ts` (which requires the `--allow-ffi` 85 | flag) will bypass the Wasm startup penalty as well as will not require the 86 | `init()` startup time. This would only work with the Deno CLI and not Deploy. 87 | -------------------------------------------------------------------------------- /advanced/jsx_dom/jsdom.md: -------------------------------------------------------------------------------- 1 | # Using jsdom with Deno 2 | 3 | [jsdom](https://github.com/jsdom/jsdom) is a pure JavaScript implementation of 4 | many web standards, notably the WHATWG DOM and HTML Standards. It's main goal is 5 | to be comprehensive and standards compliant and does not specifically consider 6 | performance. 7 | 8 | If you are interested in server side rendering, then both 9 | [deno-dom](./deno_dom.md) and [LinkeDOM](./linkedom.md) are better choices. If 10 | you are trying to run code in a "virtual" browser that needs to be standards 11 | based, then it is possible that jsdom is suitable for you. 12 | 13 | While jsdom works under the Deno CLI, it does not type check. This means you 14 | have to use the `--no-check=remote` option on the command line to avoid 15 | diagnostics stopping the execution of your programme. 16 | 17 | Having sound typing in an editor requires some changes to the workflow as well, 18 | as the way jsdom types are provided are declared as a global type definition 19 | with a globally named module, as well as leveraging the built in types from the 20 | built-in DOM libraries. 21 | 22 | This means if you want strong typing and intelligent auto-completion in your 23 | editor while using the Deno language server, you have to perform some extra 24 | steps. 25 | 26 | ### Defining an `import_map.json` 27 | 28 | You need to map the bare specifier `"jsdom"` to the imported version of jsdom. 29 | This allows Deno to correctly apply the types to the import in the way they were 30 | specified. 31 | 32 | ```json 33 | { 34 | "jsdom": "https://esm.sh/jsdom" 35 | } 36 | ``` 37 | 38 | ### Setting up a configuration file 39 | 40 | You will want to set up a `deno.jsonc` configuration file in the root of your 41 | workspace with both TypeScript library information as well as specifying the 42 | import map defined above: 43 | 44 | ```jsonc 45 | { 46 | "compilerOptions": { 47 | "lib": [ 48 | "deno.ns", 49 | "dom", 50 | "dom.iterable", 51 | "dom.asynciterable" 52 | ] 53 | }, 54 | "importMap": "./import_map.json" 55 | } 56 | ``` 57 | 58 | > Note: we are using an unpinned version of jsdom above. You should consider 59 | > pinning the version to the version you know you want to use. 60 | 61 | ## Basic example 62 | 63 | This example will take a test string and parse it as HTML and generate a DOM 64 | structure based on it. It will then query that DOM structure, picking out the 65 | first heading it encounters and print out the text content of that heading: 66 | 67 | ```ts, ignore 68 | import { JSDOM } from "jsdom"; 69 | import { assert } from "https://deno.land/std@$STD_VERSION/assert/mod.ts"; 70 | 71 | const { window: { document } } = new JSDOM( 72 | ` 73 | 74 | 75 | Hello from Deno 76 | 77 | 78 |

Hello from Deno

79 |
80 | 81 | 84 |
85 | 86 | `, 87 | { 88 | url: "https://example.com/", 89 | referrer: "https://example.org/", 90 | contentType: "text/html", 91 | storageQuota: 10000000, 92 | }, 93 | ); 94 | 95 | const h1 = document.querySelector("h1"); 96 | assert(h1); 97 | 98 | console.log(h1.textContent); 99 | ``` 100 | -------------------------------------------------------------------------------- /advanced/jsx_dom/linkedom.md: -------------------------------------------------------------------------------- 1 | # Using LinkeDOM with Deno 2 | 3 | [LinkeDOM](https://github.com/WebReflection/linkedom) is a DOM-like namespace to 4 | be used in environments, like Deno, which don't implement the DOM. 5 | 6 | LinkeDOM focuses on being fast and implementing features useful for server side 7 | rendering. It may allow you to do things that are invalid DOM operations. 8 | [deno-dom](./deno_dom.md) and [jsdom](./jsdom.md) focus on correctness. While 9 | currently deno-dom is slower than LinkeDOM in some cases, both are significantly 10 | faster than jsdom, so if you require correctness or features not related to 11 | server side rendering, consider deno-dom. 12 | 13 | While LinkeDOM works under the Deno CLI, it does not type check. While the 14 | provided types work well when using an editor like VSCode, attempting to 15 | strictly type check them, like Deno does by default, at runtime, it will fail. 16 | This is the same if you were to use `tsc` to type check the code. The maintainer 17 | has indicated they aren't interested in 18 | [fixing this issue](https://github.com/WebReflection/linkedom/issues/87). This 19 | means for Deno, you need to use the `--no-check=remote` to avoid diagnostics 20 | stopping the execution of your programme. 21 | 22 | LinkedDOM runs under Deno Deploy, along with deno_dom, but jsdom does not. 23 | 24 | ## Basic example 25 | 26 | This example will take a test string and parse it as HTML and generate a DOM 27 | structure based on it. It will then query that DOM structure, picking out the 28 | first heading it encounters and print out the text content of that heading: 29 | 30 | ```ts 31 | import { DOMParser } from "https://esm.sh/linkedom"; 32 | import { assert } from "https://deno.land/std@$STD_VERSION/assert/mod.ts"; 33 | 34 | const document = new DOMParser().parseFromString( 35 | ` 36 | 37 | 38 | Hello from Deno 39 | 40 | 41 |

Hello from Deno

42 |
43 | 44 | 47 |
48 | 49 | `, 50 | "text/html", 51 | ); 52 | 53 | assert(document); 54 | const h1 = document.querySelector("h1"); 55 | assert(h1); 56 | 57 | console.log(h1.textContent); 58 | ``` 59 | 60 | ## Alternative API 61 | 62 | For the `parseHTML()` can be better suited for certain SSR workloads. This is 63 | similar to jsdom's `JSDOM()` function, in the sense it gives you a "sandbox" of 64 | a `window` scope you can use to access API's outside of the scope of the 65 | `document`. For example: 66 | 67 | ```ts, ignore 68 | import { parseHTML } from "https://esm.sh/linkedom"; 69 | 70 | const { document, customElements, HTMLElement } = parseHTML(` 71 | 72 | 73 | Hello from Deno 74 | 75 | 76 |

Hello from Deno

77 |
78 | 79 | 82 |
83 | 84 | `); 85 | 86 | customElements.define( 87 | "custom-element", 88 | class extends HTMLElement { 89 | connectedCallback() { 90 | console.log("it works 🥳"); 91 | } 92 | }, 93 | ); 94 | 95 | document.body.appendChild(document.createElement("custom-element")); 96 | 97 | document.toString(); // the string of the document, ready to send to a client 98 | ``` 99 | -------------------------------------------------------------------------------- /advanced/jsx_dom/overview.md: -------------------------------------------------------------------------------- 1 | # Overview of JSX and DOM in Deno 2 | 3 | One of the common use cases for Deno is to handle workloads as part of web 4 | applications. Because Deno includes many of the browser APIs built-in, there is 5 | a lot of power in being able to create isomorphic code that can run both in Deno 6 | and in the browser. A powerful workload that can be handled by Deno is 7 | performing _server side rendering_ (SSR), where application state is used 8 | _server side_ to dynamically render HTML and CSS to be provided to a client. 9 | 10 | Server side rendering, when used effectively, can dramatically increase the 11 | performance of a web application by offloading heavy calculations of dynamic 12 | content to a server process allowing an application developer to minimize the 13 | JavaScript and application state that needs to be shipped to the browser. 14 | 15 | A web application is generally made up of three key technologies: 16 | 17 | - JavaScript 18 | - HTML 19 | - CSS 20 | 21 | As well as increasingly, [Web Assembly](../../runtime/webassembly.md) might play 22 | a part in a web application. 23 | 24 | These technologies combine to allow a developer to build an application in a 25 | browser using the web platform. While Deno supports a lot of web platform APIs, 26 | it generally only supports web APIs that are usable in a _server-side_ context, 27 | but in a client/browser context, the main "display" API is the Document Object 28 | Model (or DOM). There are APIs that are accessible to application logic via 29 | JavaScript that manipulate the DOM to provide a desired outcome, as well as HTML 30 | and CSS are used to structure and style the _display_ of a web application. 31 | 32 | In order to facilitate manipulation of the DOM server side and the ability to 33 | generate HTML and CSS dynamically, there are some key technologies and libraries 34 | that can be used with Deno to achieve this, which we will explore in this 35 | chapter. 36 | 37 | We will be exploring fairly low-level enabling libraries and technologies, 38 | versus a full solution or framework for server side generation of websites. 39 | 40 | ## JSX 41 | 42 | Created by the React team at Facebook, JSX is a popular DSL (domain specific 43 | language) for embedding HTML-like syntax in JavaScript. The TypeScript team also 44 | added support for the JSX syntax into TypeScript. JSX has become popular with 45 | developers as it allows mixing imperative programming logic with a declarative 46 | syntax that looks a lot like HTML. 47 | 48 | An example of what a JSX "component" might look like: 49 | 50 | ```jsx 51 | export function Greeting({ name }) { 52 | return ( 53 |
54 |

Hello {name}!

55 |
56 | ); 57 | } 58 | ``` 59 | 60 | The main challenge with JSX is that it isn't JavaScript nor is it HTML. It 61 | requires transpiling to pure JavaScript before it can be used in a browser, 62 | which then has to process that logic to manipulate the DOM in the browser. This 63 | is probably less efficient than having a browser render static HTML. 64 | 65 | This is where Deno can play a role. Deno supports JSX in both `.jsx` and `.tsx` 66 | modules and combined with a JSX runtime, Deno can be used to dynamically 67 | generate HTML to be sent to a browser client, without the need of shipping the 68 | un-transpiled source file, or the JSX runtime library to the browser. 69 | 70 | Read the [Configuring JSX in Deno](./jsx.md) section for information on how to 71 | customize the configuration of JSX in Deno. 72 | 73 | ## Document Object Model (DOM) 74 | 75 | The DOM is the main way a user interface is provided in a browser, and it 76 | exposes a set of APIs that allow it to be manipulated via JavaScript, but also 77 | allows the direct use of HTML and CSS. 78 | 79 | While Deno has a lot of web platform APIs, it does not support most of the DOM 80 | APIs related to visual representation. Having said that though, there are a few 81 | libraries that provide a lot of the APIs needed to take code that was designed 82 | to run in a web browser to be able to run under Deno, in order to generate HTML 83 | and CSS which can be shipped to a browser "pre-rendered". We will cover those in 84 | the following sections: 85 | 86 | - [Using LinkeDOM with Deno](./linkedom.md) 87 | - [Using deno-dom with Deno](./deno_dom.md) 88 | - [Using jsdom with Deno](./jsdom.md) 89 | 90 | ## CSS 91 | 92 | Cascading Style Sheets (CSS) provide styling for HTML within the DOM. There are 93 | tools which make working with CSS in a server side context easier and powerful. 94 | 95 | - [Parsing and stringifying CSS](./css.md) 96 | - [Using Twind with Deno](./twind.md) 97 | -------------------------------------------------------------------------------- /advanced/jsx_dom/twind.md: -------------------------------------------------------------------------------- 1 | # Using Twind with Deno 2 | 3 | [Twind](https://twind.dev/) is a _tailwind-in-js_ solution for using 4 | [Tailwind](https://tailwindcss.com/). Twind is particularly useful in Deno's 5 | server context, where Tailwind and CSS can be easily server side rendered, 6 | generating dynamic, performant and efficient CSS while having the usability of 7 | styling with Tailwind. 8 | 9 | ## Basic example 10 | 11 | In the following example, we will use twind to server side render an HTML page 12 | and log it to the console. It demonstrates using the `tw` function to specify 13 | grouped tailwind classes and have it rendered using only the styles specified in 14 | the document and no client side JavaScript to accomplish the _tailwind-in-js_: 15 | 16 | ```ts 17 | import { setup, tw } from "https://esm.sh/twind@0.16.16"; 18 | import { getStyleTag, virtualSheet } from "https://esm.sh/twind@0.16.16/sheets"; 19 | 20 | const sheet = virtualSheet(); 21 | 22 | setup({ 23 | theme: { 24 | fontFamily: { 25 | sans: ["Helvetica", "sans-serif"], 26 | serif: ["Times", "serif"], 27 | }, 28 | }, 29 | sheet, 30 | }); 31 | 32 | function renderBody() { 33 | return ` 34 |

Hello from Deno

35 |
36 | 37 | 40 |
41 | `; 42 | } 43 | 44 | function ssr() { 45 | sheet.reset(); 46 | const body = renderBody(); 47 | const styleTag = getStyleTag(sheet); 48 | 49 | return ` 50 | 51 | 52 | Hello from Deno 53 | ${styleTag} 54 | 55 | 56 | ${body} 57 | 58 | `; 59 | } 60 | 61 | console.log(ssr()); 62 | ``` 63 | -------------------------------------------------------------------------------- /advanced/language_server.md: -------------------------------------------------------------------------------- 1 | # The Language Server 2 | 3 | The Deno CLI comes with a built in language server that can provide an 4 | intelligent editing experience as well as a way to easily access the other tools 5 | that come built in with Deno. For most users, using the language server would be 6 | via your editor like [Visual Studio Code](../references/vscode_deno.md) or 7 | [other editors](../getting_started/setup_your_environment.md). This section of 8 | the manual is designed for those creating integrations to the language server or 9 | providing a package registry for Deno that integrates intelligently. 10 | 11 | In this section we will cover: 12 | 13 | - [An Overview of the Language Server](./language_server/overview.md) 14 | - [Import Completions and Intelligent Package Registries](./language_server/imports.md) 15 | -------------------------------------------------------------------------------- /advanced/publishing.md: -------------------------------------------------------------------------------- 1 | # Publishing Modules 2 | 3 | Deno is not prescriptive about how developers make their modules 4 | available—modules may be imported from any source. To help publish and 5 | distribute modules, separate standalone solutions are provided. 6 | 7 | ## Publishing on deno.land/x 8 | 9 | A common way to publish Deno modules is via the official 10 | [https://deno.land/x](https://deno.land/x) hosting service. It caches releases 11 | of open source modules and serves them at one easy to remember domain. 12 | 13 | To use it, modules must be developed and hosted in public repositories on 14 | GitHub. Their source is then published to deno.land/x on tag creation. They can 15 | then be accessed by using a url in the following format: 16 | 17 | ``` 18 | https://deno.land/x/@/ 19 | ``` 20 | 21 | Module versions are persistent and immutable. It is thus not possible to edit or 22 | delete a module (or version), to prevent breaking programs that rely on this 23 | module. Modules may be removed if there is a legal reason to do so (for example 24 | copyright infringement). 25 | 26 | For more details, see [Adding a Module](https://deno.land/add_module). 27 | 28 | ## Auto-generating documentation for modules 29 | 30 | When a module is published, the contents of the module is analyzed. An automated 31 | process identifies modules that contain code that Deno understands and generates 32 | documentation based on the code. For each path, including the root path, it 33 | attempts to identify the default module. In order of preference it looks for 34 | `mod`, `lib`, `main`, or `index` files with an extension that Deno understands 35 | (ts,tsx,js,jsx,mjs, or mts). When viewing the documentation for the module for a 36 | path, the default module will shown. 37 | 38 | If a default module cannot be identified, a list of modules that can be 39 | documented will be provided instead. When generating the documentation, not only 40 | is the actual code parsed to generate it, inline documentation, in the form of 41 | JSDoc (/** */) is used to enrich the documentation. Many JSDoc tags are 42 | supported. To provide module level documentation (which also becomes the path 43 | level documentation when it is included in a default module), use the @module 44 | tag at the end of the first JSDoc block in the module. 45 | 46 | ## Publishing Deno modules for Node.js/npm 47 | 48 | We have built a tool that assists in the process of taking Deno specific code 49 | and publishing it to npm to work under Node.js or other parts of the JavaScript 50 | ecosystem. See [dnt - Deno to Node.js Transform](./publishing/dnt.md). 51 | -------------------------------------------------------------------------------- /advanced/publishing/dnt.md: -------------------------------------------------------------------------------- 1 | # dnt - Publishing Deno modules for Node.js 2 | 3 | Library authors may want to make their Deno modules available to Node.js users. 4 | This is possible by using the [dnt](https://github.com/denoland/dnt) build tool. 5 | 6 | dnt allows you to develop your Deno module mostly as-is and use a single Deno 7 | script to build, type check, and test an npm package in an output directory. 8 | Once built, you only need to `npm publish` the output directory to distribute it 9 | to Node.js users. 10 | 11 | For more details, see https://github.com/denoland/dnt 12 | -------------------------------------------------------------------------------- /advanced/typescript.md: -------------------------------------------------------------------------------- 1 | # Using TypeScript 2 | 3 | Deno not only supports TypeScript out of the box, but also treats TypeScript as 4 | a first class language. This means the developer experience when authoring and 5 | importing TypeScript will be as easy and straightforward as that of JavaScript. 6 | 7 | You can run or import TypeScript without installing anything more than the Deno 8 | CLI. 9 | 10 | In this chapter, we'll discuss: 11 | 12 | - [Overview of TypeScript in Deno](./typescript/overview.md) 13 | - [Configuring TypeScript in Deno](./typescript/configuration.md) 14 | - [Types and Type Declarations](./typescript/types.md) 15 | - [Migrating to/from JavaScript](./typescript/migration.md) 16 | - [FAQs about TypeScript in Deno](./typescript/faqs.md) 17 | -------------------------------------------------------------------------------- /advanced/typescript/migration.md: -------------------------------------------------------------------------------- 1 | # Migrating to and from JavaScript 2 | 3 | One of the advantages of Deno is that it treats TypeScript and JavaScript pretty 4 | equally. This might mean that transitioning from JavaScript to TypeScript or 5 | even from TypeScript to JavaScript is something you want to accomplish. There 6 | are several features of Deno that can help with this. 7 | 8 | ## Type checking JavaScript 9 | 10 | You might have some JavaScript that you would like to ensure is more type sound 11 | but you don't want to go through a process of adding type annotations 12 | everywhere. 13 | 14 | Deno supports using the TypeScript type checker to type check JavaScript. You 15 | can mark any individual file by adding the check JavaScript pragma to the file: 16 | 17 | ```js 18 | // @ts-check 19 | ``` 20 | 21 | This will cause the type checker to infer type information about the JavaScript 22 | code and raise any issues as diagnostic issues. 23 | 24 | These can be turned on for all JavaScript files in a program by providing a 25 | configuration file with the check JS option enabled: 26 | 27 | ```json 28 | { 29 | "compilerOptions": { 30 | "checkJs": true 31 | } 32 | } 33 | ``` 34 | 35 | And setting the `--config` option on the command line. 36 | 37 | ## Using JSDoc in JavaScript 38 | 39 | If you are type checking JavaScript, or even importing JavaScript into 40 | TypeScript you can use JSDoc in JavaScript to express more types information 41 | than can just be inferred from the code itself. Deno supports this without any 42 | additional configuration, you simply need to annotate the code in line with the 43 | supported 44 | [TypeScript JSDoc](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html). 45 | For example to set the type of an array: 46 | 47 | ```js 48 | /** @type {string[]} */ 49 | const a = []; 50 | ``` 51 | 52 | ## Skipping type checking 53 | 54 | You might have TypeScript code that you are experimenting with, where the syntax 55 | is valid but not fully type safe. You can always bypass type checking for a 56 | whole program by passing the `--no-check`. 57 | 58 | You can also skip whole files being type checked, including JavaScript if you 59 | have check JS enabled, by using the no-check pragma: 60 | 61 | ```js 62 | // @ts-nocheck 63 | ``` 64 | 65 | ## Just renaming JS files to TS files 66 | 67 | While this might work in some cases, it has some severe limits in Deno. This is 68 | because Deno, by default, runs type checking in what is called _strict mode_. 69 | This means a lot of unclear or ambiguous situations where are not caught in 70 | non-strict mode will result in diagnostics being generated, and JavaScript is 71 | nothing but unclear and ambiguous when it comes to types. 72 | -------------------------------------------------------------------------------- /basics.md: -------------------------------------------------------------------------------- 1 | # Basics 2 | 3 | In this chapter, you will find Deno basics, including: 4 | 5 | - [Modules](./basics/modules.md) 6 | - [Standard Library](./basics/standard_library.md) 7 | - [Permissions](./basics/permissions.md) 8 | - [Connecting to Databases](./basics/connecting_to_databases.md) 9 | - [Using React with Deno](./basics/react.md) 10 | - [Environment Variables](./basics/env_variables.md) 11 | - [Testing](./basics/testing.md) 12 | - [Debugging Your Code](./basics/debugging_your_code.md) 13 | -------------------------------------------------------------------------------- /basics/debugging_your_code.md: -------------------------------------------------------------------------------- 1 | # Debugging Your Code 2 | 3 | Deno supports the [V8 Inspector Protocol](https://v8.dev/docs/inspector) used by 4 | Chrome, Edge and Node.js. This makes it possible to debug Deno programs using 5 | Chrome DevTools or other clients that support the protocol (for example VSCode). 6 | 7 | To activate debugging capabilities run Deno with the `--inspect`, 8 | `--inspect-wait` or `--inspect-brk` flags. 9 | 10 | The `--inspect` flag allows attaching the debugger at any point in time, 11 | `--inspect-wait` will wait for debugger to attach and start executing code, 12 | while `--inspect-brk` will wait for the debugger to attach and will pause 13 | execution on the first line of code. 14 | 15 | > ⚠️ If you use `--inspect` flag, the code will start executing immediately. If 16 | > your program is short, you might not have enough time to connect the debugger 17 | > before the program finishes execution. In such cases, try running with 18 | > `--inspect-wait` or `--inspect-brk` flag instead, or add a timeout at the end 19 | > of your code. 20 | 21 | ## Chrome Devtools 22 | 23 | Let's try debugging a program using Chrome Devtools. For this, we'll use 24 | [file_server.ts](https://deno.land/std@$STD_VERSION/http/file_server.ts) from 25 | `std`, a static file server. 26 | 27 | Use the `--inspect-brk` flag to break execution on the first line: 28 | 29 | ```shell 30 | $ deno run --inspect-brk --allow-read --allow-net https://deno.land/std@$STD_VERSION/http/file_server.ts 31 | Debugger listening on ws://127.0.0.1:9229/ws/1e82c406-85a9-44ab-86b6-7341583480b1 32 | Download https://deno.land/std@$STD_VERSION/http/file_server.ts 33 | Compile https://deno.land/std@$STD_VERSION/http/file_server.ts 34 | ... 35 | ``` 36 | 37 | In a Chromium derived browser such as Google Chrome or Microsoft Edge, open 38 | `chrome://inspect` and click `Inspect` next to target: 39 | 40 | ![chrome://inspect](../images/debugger1.jpg) 41 | 42 | It might take a few seconds after opening the DevTools to load all modules. 43 | 44 | ![DevTools opened](../images/debugger2.jpg) 45 | 46 | You might notice that DevTools pauses execution on the first line of 47 | `_constants.ts` instead of `file_server.ts`. This is expected behavior caused by 48 | the way ES modules are evaluated in JavaScript (`_constants.ts` is left-most, 49 | bottom-most dependency of `file_server.ts` so it is evaluated first). 50 | 51 | At this point all source code is available in the DevTools, so let's open up 52 | `file_server.ts` and add a breakpoint there; go to "Sources" pane and expand the 53 | tree: 54 | 55 | ![Open file_server.ts](../images/debugger3.jpg) 56 | 57 | _Looking closely you'll find duplicate entries for each file; one written 58 | regularly and one in italics. The former is compiled source file (so in the case 59 | of `.ts` files it will be emitted JavaScript source), while the latter is a 60 | source map for the file._ 61 | 62 | Next, add a breakpoint in the `listenAndServe` method: 63 | 64 | ![Break in file_server.ts](../images/debugger4.jpg) 65 | 66 | As soon as we've added the breakpoint, DevTools automatically opens up the 67 | source map file, which allows us step through the actual source code that 68 | includes types. 69 | 70 | Now that we have our breakpoints set, we can resume the execution of our script 71 | so that we can inspect an incoming request. Hit the "Resume script execution" 72 | button to do so. You might even need to hit it twice! 73 | 74 | Once our script is running, try send a request and inspect it in Devtools: 75 | 76 | ``` 77 | $ curl http://0.0.0.0:4507/ 78 | ``` 79 | 80 | ![Break in request handling](../images/debugger5.jpg) 81 | 82 | At this point we can introspect the contents of the request and go step-by-step 83 | to debug the code. 84 | 85 | ## VSCode 86 | 87 | Deno can be debugged using VSCode. This is best done with help from the official 88 | `vscode_deno` extension. Documentation for this can be found 89 | [here](../references/vscode_deno#using-the-debugger). 90 | 91 | ## JetBrains IDEs 92 | 93 | _**Note**: make sure you have 94 | [this Deno plugin](https://plugins.jetbrains.com/plugin/14382-deno) installed 95 | and enabled in Preferences / Settings | Plugins. For more information, see 96 | [this blog post](https://blog.jetbrains.com/webstorm/2020/06/deno-support-in-jetbrains-ides/)._ 97 | 98 | You can debug Deno using your JetBrains IDE by right-clicking the file you want 99 | to debug and selecting the `Debug 'Deno: '` option. 100 | 101 | ![Debug file](../images/jb-ide-debug.png) 102 | 103 | This will create a run/debug configuration with no permission flags set. If you 104 | want to configure them, open your run/debug configuration and add the required 105 | flags to the `Command` field. 106 | 107 | ## Other 108 | 109 | Any client that implements the DevTools protocol should be able to connect to a 110 | Deno process. 111 | -------------------------------------------------------------------------------- /basics/env_variables.md: -------------------------------------------------------------------------------- 1 | # Environment variables 2 | 3 | There are a few ways to use environment variables in Deno: 4 | 5 | ## Built-in `Deno.env` 6 | 7 | The Deno runtime offers built-in support for environment variables with 8 | [`Deno.env`](https://deno.land/api@v1.25.3?s=Deno.env). 9 | 10 | `Deno.env` has getter and setter methods. Here is example usage: 11 | 12 | ```ts 13 | Deno.env.set("FIREBASE_API_KEY", "examplekey123"); 14 | Deno.env.set("FIREBASE_AUTH_DOMAIN", "firebasedomain.com"); 15 | 16 | console.log(Deno.env.get("FIREBASE_API_KEY")); // examplekey123 17 | console.log(Deno.env.get("FIREBASE_AUTH_DOMAIN")); // firebasedomain.com 18 | console.log(Deno.env.has("FIREBASE_AUTH_DOMAIN")); // true 19 | ``` 20 | 21 | ## `.env` file 22 | 23 | You can also put environment variables in a `.env` file and retrieve them using 24 | `dotenv` in the standard library. 25 | 26 | Let's say you have an `.env` file that looks like this: 27 | 28 | ```sh 29 | PASSWORD=Geheimnis 30 | ``` 31 | 32 | To access the environment variables in the `.env` file, import the `load` 33 | function from the standard library. Then, import the configuration using it. 34 | 35 | ```ts 36 | import { load } from "https://deno.land/std/dotenv/mod.ts"; 37 | 38 | const env = await load(); 39 | const password = env["PASSWORD"]; 40 | 41 | console.log(password); 42 | // "Geheimnis" 43 | ``` 44 | 45 | ## `std/flags` 46 | 47 | The Deno standard library has a 48 | [`std/flags` module](https://deno.land/std@$STD_VERSION/flags/mod.ts) for 49 | parsing command line arguments. 50 | -------------------------------------------------------------------------------- /basics/import_maps.md: -------------------------------------------------------------------------------- 1 | # Import Maps 2 | 3 | In order for Deno to resolve a _bare specifier_ like `"react"` or `"lodash"`, it 4 | needs to be told where to look for it. Does `"lodash"` refer to an npm module or 5 | does it map to an https URL? 6 | 7 | ```ts, ignore 8 | import lodash from "lodash"; 9 | ``` 10 | 11 | Node and npm use `package.json` and the `node_modules` folder to do this 12 | resolution. Deno, on the other hand, uses the 13 | [import map](https://github.com/WICG/import-maps) standard. 14 | 15 | To make the above `import lodash from "lodash"` work, add the following to the 16 | [`deno.json` configuration file](../getting_started/configuration_file.md). 17 | 18 | ```json 19 | { 20 | "imports": { 21 | "lodash": "https://esm.sh/lodash@4.17.21" 22 | } 23 | } 24 | ``` 25 | 26 | The `deno.json` file is auto-discovered and acts (among other things) as an 27 | import map. 28 | [Read more about `deno.json` here](../getting_started/configuration_file.md). 29 | 30 | This also works with npm specifiers. Instead of the above, we could have also 31 | written something similar in our `deno.json` configuration file: 32 | 33 | ```json 34 | { 35 | "imports": { 36 | "lodash": "npm:lodash@^4.17" 37 | } 38 | } 39 | ``` 40 | 41 | ## Example - Using deno_std's fmt module via `fmt/` 42 | 43 | **deno.json** 44 | 45 | ```json 46 | { 47 | "imports": { 48 | "fmt/": "https://deno.land/std@$STD_VERSION/fmt/" 49 | } 50 | } 51 | ``` 52 | 53 | **color.ts** 54 | 55 | ```ts, ignore 56 | import { red } from "fmt/colors.ts"; 57 | 58 | console.log(red("hello world")); 59 | ``` 60 | 61 | ## Example - Using project root for absolute imports 62 | 63 | To use your project root for absolute imports: 64 | 65 | **deno.json** 66 | 67 | ```jsonc 68 | { 69 | "imports": { 70 | "/": "./", 71 | "./": "./" 72 | } 73 | } 74 | ``` 75 | 76 | **main.ts** 77 | 78 | ```ts, ignore 79 | import { MyUtil } from "/util.ts"; 80 | ``` 81 | 82 | This causes import specifiers starting with `/` to be resolved relative to the 83 | import map's URL or file path. 84 | 85 | ## Overriding imports 86 | 87 | The other situation where import maps can be very useful is to override imports 88 | in specific modules. 89 | 90 | Let's say you want to override the deno_std import from 0.177.0 to the latest in 91 | all of your imported modules, but for the `https://deno.land/x/example/` module 92 | you want to use files in a local `patched` directory. You can do this by using a 93 | scope in the import map that looks something like this: 94 | 95 | ```json 96 | { 97 | "imports": { 98 | "https://deno.land/std@0.177.0/": "https://deno.land/std@$STD_VERSION/" 99 | }, 100 | "scopes": { 101 | "https://deno.land/x/example/": { 102 | "https://deno.land/std@0.177.0/": "./patched/" 103 | } 104 | } 105 | } 106 | ``` 107 | 108 | ## Import Maps are for Applications 109 | 110 | It is important to note that import map configuration files are 111 | [only applied for Deno applications][scope], not in the various libraries that 112 | your application code may import. This lets you, the application author, have 113 | final say about what versions of libraries get included in your project. 114 | 115 | If you are developing a library, you should instead prefer to use the `deps.ts` 116 | pattern discussed in [Managing Dependencies]. 117 | 118 | [scope]: https://github.com/WICG/import-maps#scope 119 | [Managing Dependencies]: ../examples/manage_dependencies.md 120 | -------------------------------------------------------------------------------- /basics/modules/integrity_checking.md: -------------------------------------------------------------------------------- 1 | # Integrity Checking & Lock Files 2 | 3 | ## Introduction 4 | 5 | Let's say your module depends on remote module `https://some.url/a.ts`. When you 6 | compile your module for the first time `a.ts` is retrieved, compiled and cached. 7 | It will remain this way until you run your module on a new machine (say in 8 | production) or reload the cache (through `deno cache --reload` for example). But 9 | what happens if the content in the remote url `https://some.url/a.ts` is 10 | changed? This could lead to your production module running with different 11 | dependency code than your local module. Deno's solution to avoid this is to use 12 | integrity checking and lock files. 13 | 14 | ## Caching and lock files 15 | 16 | Deno can store and check subresource integrity for modules using a small JSON 17 | file. To opt into a lock file, either: 18 | 19 | 1. Create a `deno.json` file in the current or an ancestor directory, which will 20 | automatically create an additive lockfile at `deno.lock`. 21 | 2. Use the `--lock=deno.lock` to enable and specify lock file checking. To 22 | update or create a lock use `--lock=deno.lock --lock-write`. The 23 | `--lock=deno.lock` tells Deno what the lock file to use is, while the 24 | `--lock-write` is used to output dependency hashes to the lock file 25 | (`--lock-write` must be used in conjunction with `--lock`). 26 | 27 | A `deno.lock` might look like this, storing a hash of the file against the 28 | dependency: 29 | 30 | ```json 31 | { 32 | "https://deno.land/std@$STD_VERSION/textproto/mod.ts": "3118d7a42c03c242c5a49c2ad91c8396110e14acca1324e7aaefd31a999b71a4", 33 | "https://deno.land/std@$STD_VERSION/io/util.ts": "ae133d310a0fdcf298cea7bc09a599c49acb616d34e148e263bcb02976f80dee", 34 | "https://deno.land/std@$STD_VERSION/async/delay.ts": "35957d585a6e3dd87706858fb1d6b551cb278271b03f52c5a2cb70e65e00c26a", 35 | ... 36 | } 37 | ``` 38 | 39 | ### Auto-generated lockfile 40 | 41 | As mentioned above, when a Deno configuration file is resolved (ex. `deno.json`) 42 | then an additive lockfile will be automatically generated. By default, the path 43 | of this lockfile will be `deno.lock`. You can change this path by updating your 44 | `deno.json` to specify this: 45 | 46 | ```jsonc 47 | { 48 | "lock": "./lock.file" 49 | } 50 | ``` 51 | 52 | Or disable automatically creating and validating a lockfile by specifying: 53 | 54 | ```jsonc 55 | { 56 | "lock": false 57 | } 58 | ``` 59 | 60 | ### Using `--lock` and `--lock-write` flags 61 | 62 | A typical workflow will look like this: 63 | 64 | **src/deps.ts** 65 | 66 | ```ts, ignore 67 | // Add a new dependency to "src/deps.ts", used somewhere else. 68 | export { xyz } from "https://unpkg.com/xyz-lib@v0.9.0/lib.ts"; 69 | ``` 70 | 71 | Then: 72 | 73 | ```shell 74 | # Create/update the lock file "deno.lock". 75 | deno cache --lock=deno.lock --lock-write src/deps.ts 76 | 77 | # Include it when committing to source control. 78 | git add -u deno.lock 79 | git commit -m "feat: Add support for xyz using xyz-lib" 80 | git push 81 | ``` 82 | 83 | Collaborator on another machine -- in a freshly cloned project tree: 84 | 85 | ```shell 86 | # Download the project's dependencies into the machine's cache, integrity 87 | # checking each resource. 88 | deno cache --reload --lock=deno.lock src/deps.ts 89 | 90 | # Done! You can proceed safely. 91 | deno test --allow-read src 92 | ``` 93 | 94 | ## Runtime verification 95 | 96 | Like caching above, you can also use lock files during use of the `deno run` sub 97 | command, validating the integrity of any locked modules during the run. Remember 98 | that this only validates against dependencies previously added to the lock file. 99 | 100 | You can take this a step further as well by using the `--cached-only` flag to 101 | require that remote dependencies are already cached. 102 | 103 | ```shell 104 | deno run --lock=deno.lock --cached-only mod.ts 105 | ``` 106 | 107 | This will fail if there are any dependencies in the dependency tree for mod.ts 108 | which are not yet cached. 109 | 110 | 111 | -------------------------------------------------------------------------------- /basics/modules/private.md: -------------------------------------------------------------------------------- 1 | # Private Modules and Repositories 2 | 3 | There may be instances where you want to load a remote module that is located in 4 | a _private_ repository, like a private repository on GitHub. 5 | 6 | Deno supports sending bearer tokens when requesting a remote module. Bearer 7 | tokens are the predominant type of access token used with OAuth 2.0, and are 8 | broadly supported by hosting services (e.g., GitHub, GitLab, Bitbucket, 9 | Cloudsmith, etc.). 10 | 11 | ## DENO_AUTH_TOKENS 12 | 13 | The Deno CLI will look for an environment variable named `DENO_AUTH_TOKENS` to 14 | determine what authentication tokens it should consider using when requesting 15 | remote modules. The value of the environment variable is in the format of _n_ 16 | number of tokens delimited by a semi-colon (`;`) where each token is either: 17 | 18 | - a bearer token in the format of `{token}@{hostname[:port]}` or 19 | 20 | - basic auth data in the format of `{username}:{password}@{hostname[:port]}` 21 | 22 | For example, a single token for `deno.land` would look something like this: 23 | 24 | ```sh 25 | DENO_AUTH_TOKENS=a1b2c3d4e5f6@deno.land 26 | ``` 27 | 28 | or: 29 | 30 | ```sh 31 | DENO_AUTH_TOKENS=username:password@deno.land 32 | ``` 33 | 34 | And multiple tokens would look like this: 35 | 36 | ```sh 37 | DENO_AUTH_TOKENS=a1b2c3d4e5f6@deno.land;f1e2d3c4b5a6@example.com:8080;username:password@deno.land 38 | ``` 39 | 40 | When Deno goes to fetch a remote module, where the hostname matches the hostname 41 | of the remote module, Deno will set the `Authorization` header of the request to 42 | the value of `Bearer {token}` or `Basic {base64EncodedData}`. This allows the 43 | remote server to recognize that the request is an authorized request tied to a 44 | specific authenticated user, and provide access to the appropriate resources and 45 | modules on the server. 46 | 47 | ## GitHub 48 | 49 | To access private repositories on GitHub, you would need to issue yourself a 50 | _personal access token_. You do this by logging into GitHub and going under 51 | _Settings -> Developer settings -> Personal access tokens_: 52 | 53 | ![Personal access tokens settings on GitHub](../../images/private-pat.png) 54 | 55 | You would then choose to _Generate new token_ and give your token a description 56 | and appropriate access: 57 | 58 | ![Creating a new personal access token on GitHub](../../images/private-github-new-token.png) 59 | 60 | And once created GitHub will display the new token a single time, the value of 61 | which you would want to use in the environment variable: 62 | 63 | ![Display of newly created token on GitHub](../../images/private-github-token-display.png) 64 | 65 | In order to access modules that are contained in a private repository on GitHub, 66 | you would want to use the generated token in the `DENO_AUTH_TOKENS` environment 67 | variable scoped to the `raw.githubusercontent.com` hostname. For example: 68 | 69 | ```sh 70 | DENO_AUTH_TOKENS=a1b2c3d4e5f6@raw.githubusercontent.com 71 | ``` 72 | 73 | This should allow Deno to access any modules that the user who the token was 74 | issued for has access to. 75 | 76 | When the token is incorrect, or the user does not have access to the module, 77 | GitHub will issue a `404 Not Found` status, instead of an unauthorized status. 78 | So if you are getting errors that the modules you are trying to access are not 79 | found on the command line, check the environment variable settings and the 80 | personal access token settings. 81 | 82 | In addition, `deno run -L debug` should print out a debug message about the 83 | number of tokens that are parsed out of the environment variable. It will print 84 | an error message if it feels any of the tokens are malformed. It won't print any 85 | details about the tokens for security purposes. 86 | -------------------------------------------------------------------------------- /basics/modules/proxies.md: -------------------------------------------------------------------------------- 1 | # Proxies 2 | 3 | Deno supports proxies for module downloads and the Web standard `fetch` API. 4 | 5 | Proxy configuration is read from environmental variables: `HTTP_PROXY`, 6 | `HTTPS_PROXY` and `NO_PROXY`. 7 | 8 | In case of Windows, if environment variables are not found Deno falls back to 9 | reading proxies from registry. 10 | -------------------------------------------------------------------------------- /basics/modules/reloading_modules.md: -------------------------------------------------------------------------------- 1 | # Reloading Modules 2 | 3 | By default, a module in the cache will be reused without fetching or 4 | re-compiling it. Sometimes this is not desirable and you can force deno to 5 | refetch and recompile modules into the cache. You can invalidate your local 6 | `DENO_DIR` cache using the `--reload` flag of the `deno cache` subcommand. It's 7 | usage is described below: 8 | 9 | ## To reload everything 10 | 11 | ```bash 12 | deno cache --reload my_module.ts 13 | ``` 14 | 15 | ## To reload specific modules 16 | 17 | Sometimes we want to upgrade only some modules. You can control it by passing an 18 | argument to a `--reload` flag. 19 | 20 | To reload all \$STD_VERSION standard modules: 21 | 22 | ```bash 23 | deno cache --reload=https://deno.land/std@$STD_VERSION my_module.ts 24 | ``` 25 | 26 | To reload specific modules (in this example - colors and file system copy) use a 27 | comma to separate URLs. 28 | 29 | ```bash 30 | deno cache --reload=https://deno.land/std@$STD_VERSION/fs/copy.ts,https://deno.land/std@$STD_VERSION/fmt/colors.ts my_module.ts 31 | ``` 32 | 33 | 34 | -------------------------------------------------------------------------------- /basics/react.md: -------------------------------------------------------------------------------- 1 | # Using React with Deno 2 | 3 | To use React with Deno, we recommend using one of the third-party frameworks 4 | below. 5 | 6 | If you want to better understand how JSX and Deno interface under the hood, read 7 | on [here](../advanced/jsx_dom). 8 | 9 | Note: Fresh and Aleph.js provide a framework for developing React-like websites, 10 | but use an alternative foundational technology, Preact to provide a better, more 11 | performant experience. 12 | 13 | ## Fresh 14 | 15 | [Fresh](https://fresh.deno.dev/) is the most popular React framework for Deno. 16 | It uses a model where you send no JavaScript to clients by default. The majority 17 | of rendering is done on a server, and the client is only responsible for 18 | re-rendering small 19 | [islands of interactivity](https://jasonformat.com/islands-architecture/). This 20 | means the developer explicitly opts in to client side rendering for specific 21 | components. 22 | 23 | ## Aleph 24 | 25 | [Aleph.js](https://alephjs.org/docs/get-started) is the second most popular 26 | React framework for Deno. It gives you the same sort of quick-start with React 27 | as Create-React-App. Like Next.js, Aleph provides SSR and SSG out of the box in 28 | order to allow developers to create SEO-friendly apps. In addition, Aleph 29 | provides some other built-in features that don't come out of the box in Next.js, 30 | such as: 31 | 32 | - Hot Reloading (Using React Fast Refresh) 33 | - ESM Import Syntax (No need for webpack) 34 | - TypeScript-Ready 35 | -------------------------------------------------------------------------------- /basics/standard_library.md: -------------------------------------------------------------------------------- 1 | # Standard Library 2 | 3 | Deno provides a set of standard modules that are audited by the core team and 4 | are guaranteed to work with Deno. 5 | 6 | Standard library is available at: https://deno.land/std@$STD_VERSION 7 | 8 | ## Versioning and stability 9 | 10 | Standard library is not yet stable and therefore it is versioned differently 11 | than Deno. For latest release consult https://deno.land/std@$STD_VERSION or 12 | https://deno.land/std@$STD_VERSION/version.ts. The standard library is released 13 | each time Deno is released. 14 | 15 | We strongly suggest to always use imports with pinned version of standard 16 | library to avoid unintended changes. For example, rather than linking to the 17 | default branch of code, which may change at any time, potentially causing 18 | compilation errors or unexpected behavior: 19 | 20 | ```typescript 21 | // import the latest release, this should be avoided 22 | import { copy } from "https://deno.land/std/fs/copy.ts"; 23 | ``` 24 | 25 | instead, use a version of the std library which is immutable and will not 26 | change: 27 | 28 | ```typescript 29 | // imports from v$STD_VERSION of std, never changes 30 | import { copy } from "https://deno.land/std@$STD_VERSION/fs/copy.ts"; 31 | ``` 32 | -------------------------------------------------------------------------------- /basics/testing/coverage.md: -------------------------------------------------------------------------------- 1 | # Test Coverage 2 | 3 | Deno will collect test coverage into a directory for your code if you specify 4 | the `--coverage` flag when starting `deno test`. 5 | 6 | This coverage information is acquired directly from the JavaScript engine (V8) 7 | which is very accurate. 8 | 9 | This can then be further processed from the internal format into well known 10 | formats by the `deno coverage` tool. 11 | 12 | > ⚠️ To ensure consistent coverage results, make sure to process coverage data 13 | > immediately after running tests. Otherwise source code and collected coverage 14 | > data might get out of sync and unexpectedly show uncovered lines. 15 | 16 | ```bash 17 | # Go into your project's working directory 18 | git clone https://github.com/oakserver/oak && cd oak 19 | 20 | # Collect your coverage profile with deno test --coverage= 21 | deno test --coverage=cov_profile 22 | 23 | # From this you can get a pretty printed diff of uncovered lines 24 | deno coverage cov_profile 25 | 26 | # Or generate an lcov report 27 | deno coverage cov_profile --lcov --output=cov_profile.lcov 28 | 29 | # Which can then be further processed by tools like genhtml 30 | genhtml -o cov_profile/html cov_profile.lcov 31 | ``` 32 | 33 | By default, `deno coverage` will exclude any files matching the regular 34 | expression `test\.(ts|tsx|mts|js|mjs|jsx|cjs|cts)` and only consider including 35 | specifiers matching the regular expression `^file:` - ie. remote files will be 36 | excluded from coverage report. 37 | 38 | These filters can be overridden using the `--exclude` and `--include` flags. A 39 | module specifier must _match_ the include_regular expression and _not match_ the 40 | exclude_ expression for it to be a part of the report. 41 | -------------------------------------------------------------------------------- /basics/testing/documentation.md: -------------------------------------------------------------------------------- 1 | # Documentation Tests 2 | 3 | Deno supports type-checking your documentation examples. 4 | 5 | This makes sure that examples within your documentation are up to date and 6 | working. 7 | 8 | The basic idea is this: 9 | 10 | ````ts 11 | /** 12 | * # Examples 13 | * 14 | * ```ts 15 | * const x = 42; 16 | * ``` 17 | */ 18 | ```` 19 | 20 | The triple backticks mark the start and end of code blocks, the language is 21 | determined by the language identifier attribute which may be any of the 22 | following: 23 | 24 | - `js` 25 | - `jsx` 26 | - `ts` 27 | - `tsx` 28 | 29 | If no language identifier is specified then the language is inferred from media 30 | type of the source document that the code block is extracted from. 31 | 32 | If this example was in a file named foo.ts, running `deno test --doc foo.ts` 33 | will extract this example, and then type-check it as a standalone module living 34 | in the same directory as the module being documented. 35 | 36 | To document your exports, import the module using a relative path specifier: 37 | 38 | ````ts 39 | /** 40 | * # Examples 41 | * 42 | * ```ts 43 | * import { foo } from "./foo.ts"; 44 | * ``` 45 | */ 46 | export function foo(): string { 47 | return "foo"; 48 | } 49 | ```` 50 | -------------------------------------------------------------------------------- /basics/testing/sanitizers.md: -------------------------------------------------------------------------------- 1 | # Test Sanitizers 2 | 3 | The test runner offers several sanitizers to ensure that the test behaves in a 4 | reasonable and expected way. 5 | 6 | ## Resource sanitizer 7 | 8 | Certain actions in Deno create resources in the resource table 9 | ([learn more here](../../references/contributing/architecture.md)). 10 | 11 | These resources should be closed after you are done using them. 12 | 13 | For each test definition, the test runner checks that all resources created in 14 | this test have been closed. This is to prevent resource 'leaks'. This is enabled 15 | by default for all tests, but can be disabled by setting the `sanitizeResources` 16 | boolean to false in the test definition. 17 | 18 | ```ts 19 | Deno.test({ 20 | name: "leaky resource test", 21 | async fn() { 22 | await Deno.open("hello.txt"); 23 | }, 24 | sanitizeResources: false, 25 | }); 26 | ``` 27 | 28 | ## Op sanitizer 29 | 30 | The same is true for async operation like interacting with the filesystem. The 31 | test runner checks that each operation you start in the test is completed before 32 | the end of the test. This is enabled by default for all tests, but can be 33 | disabled by setting the `sanitizeOps` boolean to false in the test definition. 34 | 35 | ```ts 36 | Deno.test({ 37 | name: "leaky operation test", 38 | fn() { 39 | crypto.subtle.digest( 40 | "SHA-256", 41 | new TextEncoder().encode("a".repeat(100000000)), 42 | ); 43 | }, 44 | sanitizeOps: false, 45 | }); 46 | ``` 47 | 48 | ## Exit sanitizer 49 | 50 | There's also the exit sanitizer which ensures that tested code doesn't call 51 | `Deno.exit()` signaling a false test success. 52 | 53 | This is enabled by default for all tests, but can be disabled by setting the 54 | `sanitizeExit` boolean to false in the test definition. 55 | 56 | ```ts 57 | Deno.test({ 58 | name: "false success", 59 | fn() { 60 | Deno.exit(0); 61 | }, 62 | sanitizeExit: false, 63 | }); 64 | 65 | // This test never runs, because the process exits during "false success" test 66 | Deno.test({ 67 | name: "failing test", 68 | fn() { 69 | throw new Error("this test fails"); 70 | }, 71 | }); 72 | ``` 73 | -------------------------------------------------------------------------------- /examples.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | In this chapter you can find some example programs that you can use to learn 4 | more about the runtime. 5 | 6 | ## Basic 7 | 8 | - [Hello World](./examples/hello_world.md) 9 | - [Manage Dependencies](./examples/manage_dependencies.md) 10 | - [Fetch Data](./examples/fetch_data.md) 11 | - [Read and Write Files](./examples/read_write_files.md) 12 | - [Hashbang](./examples/hashbang.md) 13 | 14 | ## Advanced 15 | 16 | - [Unix cat Program](./examples/unix_cat.md) 17 | - [HTTP Web Server](./examples/http_server.md) 18 | - [File Server](./examples/file_server.md) 19 | - [TCP echo Server](./examples/tcp_echo.md) 20 | - [Creating a Subprocess](./examples/subprocess.md) 21 | - [OS Signals](./examples/os_signals.md) 22 | - [File System Events](./examples/file_system_events.md) 23 | - [Module Metadata](./examples/module_metadata.md) 24 | 25 | Additional examples can by found at 26 | [Deno by Example](https://examples.deno.land/). 27 | -------------------------------------------------------------------------------- /examples/fetch_data.md: -------------------------------------------------------------------------------- 1 | # Fetch Data 2 | 3 | ## Concepts 4 | 5 | - Like browsers, Deno implements web standard APIs such as 6 | [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). 7 | - Deno is secure by default, meaning explicit permission must be granted to 8 | access the network. 9 | - See also: Deno's [permissions](../basics/permissions.md) model. 10 | 11 | ## Overview 12 | 13 | When building any sort of web application developers will usually need to 14 | retrieve data from somewhere else on the web. This works no differently in Deno 15 | than in any other JavaScript application, just call the `fetch()` method. For 16 | more information on fetch read the 17 | [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). 18 | 19 | The exception with Deno occurs when running a script which makes a call over the 20 | web. Deno is secure by default which means access to IO (Input / Output) is 21 | prohibited. To make a call over the web Deno must be explicitly told it is ok to 22 | do so. This is achieved by adding the `--allow-net` flag to the `deno run` 23 | command. 24 | 25 | ## Example 26 | 27 | **Command:** `deno run --allow-net fetch.ts` 28 | 29 | ```js 30 | /** 31 | * Output: JSON Data 32 | */ 33 | const jsonResponse = await fetch("https://api.github.com/users/denoland"); 34 | const jsonData = await jsonResponse.json(); 35 | console.log(jsonData); 36 | 37 | /** 38 | * Output: HTML Data 39 | */ 40 | const textResponse = await fetch("https://deno.land/"); 41 | const textData = await textResponse.text(); 42 | console.log(textData); 43 | 44 | /** 45 | * Output: Error Message 46 | */ 47 | try { 48 | await fetch("https://does.not.exist/"); 49 | } catch (error) { 50 | console.log(error); 51 | } 52 | ``` 53 | 54 | ## Files and Streams 55 | 56 | Like in browsers, sending and receiving large files is possible thanks to the 57 | [Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API). 58 | [`Deno.FsFile`](https://deno.land/api@$CLI_VERSION?s=Deno.FsFile) API provides 59 | two properties: 60 | [`readable`](https://deno.land/api@$CLI_VERSION?s=Deno.FsFile#prop_readable) and 61 | [`writable`](https://deno.land/api@$CLI_VERSION?s=Deno.FsFile#prop_writable), 62 | which can be used to convert a Deno file into a writable or readable stream. 63 | 64 | **Command:** `deno run --allow-read --allow-write --allow-net fetch_file.ts` 65 | 66 | ```ts 67 | /** 68 | * Receiving a file 69 | */ 70 | const fileResponse = await fetch("https://deno.land/logo.svg"); 71 | 72 | if (fileResponse.body) { 73 | const file = await Deno.open("./logo.svg", { write: true, create: true }); 74 | await fileResponse.body.pipeTo(file.writable); 75 | } 76 | 77 | /** 78 | * Sending a file 79 | */ 80 | const file = await Deno.open("./logo.svg", { read: true }); 81 | 82 | await fetch("https://example.com/", { 83 | method: "POST", 84 | body: file.readable, 85 | }); 86 | ``` 87 | -------------------------------------------------------------------------------- /examples/file_server.md: -------------------------------------------------------------------------------- 1 | # File Server 2 | 3 | ## Concepts 4 | 5 | - Use [Deno.open](/api?s=Deno.open) to read a file's content in chunks. 6 | - Transform a Deno file into a 7 | [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). 8 | - Use Deno's integrated HTTP server to run your own file server. 9 | 10 | ## Overview 11 | 12 | Sending files over the network is a common requirement. As seen in the 13 | [Fetch Data example](./fetch_data.md), because files can be of any size, it is 14 | important to use streams in order to prevent having to load entire files into 15 | memory. 16 | 17 | ## Example 18 | 19 | **Command:** `deno run --allow-read=. --allow-net file_server.ts` 20 | 21 | ```ts 22 | // Start listening on port 8080 of localhost. 23 | const server = Deno.listen({ port: 8080 }); 24 | console.log("File server running on http://localhost:8080/"); 25 | 26 | for await (const conn of server) { 27 | handleHttp(conn).catch(console.error); 28 | } 29 | 30 | async function handleHttp(conn: Deno.Conn) { 31 | const httpConn = Deno.serveHttp(conn); 32 | for await (const requestEvent of httpConn) { 33 | // Use the request pathname as filepath 34 | const url = new URL(requestEvent.request.url); 35 | const filepath = decodeURIComponent(url.pathname); 36 | 37 | // Try opening the file 38 | let file; 39 | try { 40 | file = await Deno.open("." + filepath, { read: true }); 41 | } catch { 42 | // If the file cannot be opened, return a "404 Not Found" response 43 | const notFoundResponse = new Response("404 Not Found", { status: 404 }); 44 | await requestEvent.respondWith(notFoundResponse); 45 | continue; 46 | } 47 | 48 | // Build a readable stream so the file doesn't have to be fully loaded into 49 | // memory while we send it 50 | const readableStream = file.readable; 51 | 52 | // Build and send the response 53 | const response = new Response(readableStream); 54 | await requestEvent.respondWith(response); 55 | } 56 | } 57 | ``` 58 | 59 | ## Using the `std/http` file server 60 | 61 | The Deno standard library provides you with a 62 | [file server](https://deno.land/std@$STD_VERSION/http/file_server.ts) so that 63 | you don't have to write your own. 64 | 65 | To use it, first install the remote script to your local file system. This will 66 | install the script to the Deno installation root's bin directory, e.g. 67 | `/home/alice/.deno/bin/file_server`. 68 | 69 | ```shell 70 | deno install --allow-net --allow-read https://deno.land/std@$STD_VERSION/http/file_server.ts 71 | ``` 72 | 73 | You can now run the script with the simplified script name. Run it: 74 | 75 | ```shell 76 | $ file_server . 77 | Downloading https://deno.land/std@$STD_VERSION/http/file_server.ts... 78 | [...] 79 | HTTP server listening on http://0.0.0.0:4507/ 80 | ``` 81 | 82 | Now go to [http://0.0.0.0:4507/](http://0.0.0.0:4507/) in your web browser to 83 | see your local directory contents. 84 | 85 | The complete list of options are available via: 86 | 87 | ```shell 88 | file_server --help 89 | ``` 90 | 91 | Example output: 92 | 93 | ``` 94 | Deno File Server 95 | Serves a local directory in HTTP. 96 | INSTALL: 97 | deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts 98 | USAGE: 99 | file_server [path] [options] 100 | OPTIONS: 101 | -h, --help Prints help information 102 | -p, --port Set port 103 | --cors Enable CORS via the "Access-Control-Allow-Origin" header 104 | --host Hostname (default is 0.0.0.0) 105 | -c, --cert TLS certificate file (enables TLS) 106 | -k, --key TLS key file (enables TLS) 107 | --no-dir-listing Disable directory listing 108 | All TLS options are required when one is provided. 109 | ``` 110 | -------------------------------------------------------------------------------- /examples/file_system_events.md: -------------------------------------------------------------------------------- 1 | # File System Events 2 | 3 | ## Concepts 4 | 5 | - Use [Deno.watchFs](/api?s=Deno.watchFs) to watch for file system events. 6 | - Results may vary between operating systems. 7 | 8 | ## Example 9 | 10 | To poll for file system events in the current directory: 11 | 12 | ```ts 13 | /** 14 | * watcher.ts 15 | */ 16 | const watcher = Deno.watchFs("."); 17 | for await (const event of watcher) { 18 | console.log(">>>> event", event); 19 | // Example event: { kind: "create", paths: [ "/home/alice/deno/foo.txt" ] } 20 | } 21 | ``` 22 | 23 | Run with: 24 | 25 | ```shell 26 | deno run --allow-read watcher.ts 27 | ``` 28 | 29 | Now try adding, removing and modifying files in the same directory as 30 | `watcher.ts`. 31 | 32 | Note that the exact ordering of the events can vary between operating systems. 33 | This feature uses different syscalls depending on the platform: 34 | 35 | - Linux: [inotify](https://man7.org/linux/man-pages/man7/inotify.7.html) 36 | - macOS: 37 | [FSEvents](https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html) 38 | - Windows: 39 | [ReadDirectoryChangesW](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw) 40 | -------------------------------------------------------------------------------- /examples/hashbang.md: -------------------------------------------------------------------------------- 1 | # Making Scripts Executable With a Hashbang (Shebang) 2 | 3 | ## Concepts 4 | 5 | - [Deno.env] provides the environment variables. 6 | - [env] runs a program in a modified environment. 7 | 8 | ## Overview 9 | 10 | Making Deno scripts executable can come in handy when creating small tools. 11 | 12 | Note: Hashbangs do not work on Windows. 13 | 14 | ## Example 15 | 16 | In this program we give the context permission to access the environment 17 | variables and print the Deno installation path. 18 | 19 | ```ts, ignore 20 | #!/usr/bin/env -S deno run --allow-env 21 | 22 | /** 23 | * hashbang.ts 24 | */ 25 | 26 | const path = Deno.env.get("DENO_INSTALL"); 27 | 28 | console.log("Deno Install Path:", path); 29 | ``` 30 | 31 | ### Permissions 32 | 33 | You may require to give the script execution permissions. 34 | 35 | #### Unix 36 | 37 | ```shell 38 | chmod +x hashbang.ts 39 | ``` 40 | 41 | ### Execute 42 | 43 | Start the script by calling it like any other command: 44 | 45 | ```shell 46 | ./hashbang.ts 47 | ``` 48 | 49 | ## Details 50 | 51 | - A hashbang has to be placed in the first line. 52 | 53 | - `-S` splits the command into arguments. 54 | 55 | - End the file name in `.ts` for the script to be interpreted as TypeScript. 56 | 57 | ## Using hashbang in files with no extension 58 | 59 | You may wish to not use an extension for your script's filename. In this case, 60 | you can supply one by using the `--ext` flag: 61 | 62 | ```shell, ignore 63 | $ cat my_script 64 | #!/usr/bin/env -S deno run --allow-env --ext=js 65 | console.log("Hello!"); 66 | $ ./my_script 67 | Hello! 68 | ``` 69 | 70 | [Deno.env]: /api?s=Deno.env 71 | [env]: https://www.man7.org/linux/man-pages/man1/env.1.html 72 | -------------------------------------------------------------------------------- /examples/hello_world.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | 3 | ## Concepts 4 | 5 | - Deno can run JavaScript or TypeScript out of the box with no additional tools 6 | or config required. 7 | 8 | ## Overview 9 | 10 | Deno is a secure runtime for both JavaScript and TypeScript. As the hello world 11 | examples below highlight the same functionality can be created in JavaScript or 12 | TypeScript, and Deno will execute both. 13 | 14 | ## JavaScript 15 | 16 | In this JavaScript example the message `Hello [name]` is printed to the console 17 | and the code ensures the name provided is capitalized. 18 | 19 | **Command:** `deno run hello-world.js` 20 | 21 | ```js 22 | /** 23 | * hello-world.js 24 | */ 25 | function capitalize(word) { 26 | return word.charAt(0).toUpperCase() + word.slice(1); 27 | } 28 | 29 | function hello(name) { 30 | return "Hello " + capitalize(name); 31 | } 32 | 33 | console.log(hello("john")); 34 | console.log(hello("Sarah")); 35 | console.log(hello("kai")); 36 | 37 | /** 38 | * Output: 39 | * 40 | * Hello John 41 | * Hello Sarah 42 | * Hello Kai 43 | */ 44 | ``` 45 | 46 | ## TypeScript 47 | 48 | This TypeScript example is exactly the same as the JavaScript example above, the 49 | code just has the additional type information which TypeScript supports. 50 | 51 | The `deno run` command is exactly the same, it just references a `*.ts` file 52 | rather than a `*.js` file. 53 | 54 | **Command:** `deno run hello-world.ts` 55 | 56 | ```ts 57 | /** 58 | * hello-world.ts 59 | */ 60 | function capitalize(word: string): string { 61 | return word.charAt(0).toUpperCase() + word.slice(1); 62 | } 63 | 64 | function hello(name: string): string { 65 | return "Hello " + capitalize(name); 66 | } 67 | 68 | console.log(hello("john")); 69 | console.log(hello("Sarah")); 70 | console.log(hello("kai")); 71 | 72 | /** 73 | * Output: 74 | * 75 | * Hello John 76 | * Hello Sarah 77 | * Hello Kai 78 | */ 79 | ``` 80 | -------------------------------------------------------------------------------- /examples/http_server.md: -------------------------------------------------------------------------------- 1 | # Simple HTTP Web Server 2 | 3 | ## Concepts 4 | 5 | - Use Deno's integrated HTTP server to run your own web server. 6 | 7 | ## Overview 8 | 9 | With just a few lines of code you can run your own HTTP web server with control 10 | over the response status, request headers and more. 11 | 12 | ## Using the `Deno.listen` 13 | 14 | In this example, the user-agent of the client is returned to the client: 15 | 16 | **webserver.ts**: 17 | 18 | ```ts 19 | // Start listening on port 8080 of localhost. 20 | const server = Deno.listen({ port: 8080 }); 21 | console.log(`HTTP webserver running. Access it at: http://localhost:8080/`); 22 | 23 | // Connections to the server will be yielded up as an async iterable. 24 | for await (const conn of server) { 25 | // In order to not be blocking, we need to handle each connection individually 26 | // without awaiting the function 27 | serveHttp(conn); 28 | } 29 | 30 | async function serveHttp(conn: Deno.Conn) { 31 | // This "upgrades" a network connection into an HTTP connection. 32 | const httpConn = Deno.serveHttp(conn); 33 | // Each request sent over the HTTP connection will be yielded as an async 34 | // iterator from the HTTP connection. 35 | for await (const requestEvent of httpConn) { 36 | // The native HTTP server uses the web standard `Request` and `Response` 37 | // objects. 38 | const body = `Your user-agent is:\n\n${ 39 | requestEvent.request.headers.get("user-agent") ?? "Unknown" 40 | }`; 41 | // The requestEvent's `.respondWith()` method is how we send the response 42 | // back to the client. 43 | requestEvent.respondWith( 44 | new Response(body, { 45 | status: 200, 46 | }), 47 | ); 48 | } 49 | } 50 | ``` 51 | 52 | Then run this with: 53 | 54 | ```shell 55 | deno run --allow-net webserver.ts 56 | ``` 57 | 58 | Then navigate to `http://localhost:8080/` in a browser. 59 | 60 | ### Using the `Deno.serve` 61 | 62 | **webserver.ts**: 63 | 64 | ```ts 65 | const port = 8080; 66 | 67 | const handler = (request: Request): Response => { 68 | const body = `Your user-agent is:\n\n${ 69 | request.headers.get("user-agent") ?? "Unknown" 70 | }`; 71 | 72 | return new Response(body, { status: 200 }); 73 | }; 74 | 75 | console.log(`HTTP webserver running. Access it at: http://localhost:8080/`); 76 | Deno.serve({ port }, handler); 77 | ``` 78 | 79 | Then run this with: 80 | 81 | ```shell 82 | deno run --allow-net webserver.ts 83 | ``` 84 | -------------------------------------------------------------------------------- /examples/manage_dependencies.md: -------------------------------------------------------------------------------- 1 | # Managing Dependencies 2 | 3 | ## Concepts 4 | 5 | - Deno uses URLs for dependency management. 6 | - One convention places all these dependent URLs into a local `deps.ts` file. 7 | Functionality is then exported out of `deps.ts` for use by local modules. 8 | - Continuing this convention, dev only dependencies can be kept in a 9 | `dev_deps.ts` file. 10 | - See also [Modules](../basics/modules.md) 11 | 12 | ## Overview 13 | 14 | In Deno there is no concept of a package manager as external modules are 15 | imported directly into local modules. This raises the question of how to manage 16 | remote dependencies without a package manager. In big projects with many 17 | dependencies it will become cumbersome and time consuming to update modules if 18 | they are all imported individually into individual modules. 19 | 20 | The standard practice for solving this problem in Deno is to create a `deps.ts` 21 | file. All required remote dependencies are referenced in this file and the 22 | required methods and classes are re-exported. The dependent local modules then 23 | reference the `deps.ts` rather than the remote dependencies. If now for example 24 | one remote dependency is used in several files, upgrading to a new version of 25 | this remote dependency is much simpler as this can be done just within 26 | `deps.ts`. 27 | 28 | With all dependencies centralized in `deps.ts`, managing these becomes easier. 29 | Dev dependencies can also be managed in a separate `dev_deps.ts` file, allowing 30 | clean separation between dev only and production dependencies. 31 | 32 | ## Example 33 | 34 | ```ts 35 | /** 36 | * deps.ts 37 | * 38 | * This module re-exports the required methods from the dependant remote Ramda module. 39 | */ 40 | export { 41 | add, 42 | multiply, 43 | } from "https://x.nest.land/ramda@0.27.0/source/index.js"; 44 | ``` 45 | 46 | In this example the same functionality is created as is the case in the 47 | [local and remote import examples](../basics/modules.md). But in this case 48 | instead of the Ramda module being referenced directly it is referenced by proxy 49 | using a local `deps.ts` module. 50 | 51 | **Command:** `deno run example.ts` 52 | 53 | ```ts, ignore 54 | /** 55 | * example.ts 56 | */ 57 | 58 | import { add, multiply } from "./deps.ts"; 59 | 60 | function totalCost(outbound: number, inbound: number, tax: number): number { 61 | return multiply(add(outbound, inbound), tax); 62 | } 63 | 64 | console.log(totalCost(19, 31, 1.2)); 65 | console.log(totalCost(45, 27, 1.15)); 66 | 67 | /** 68 | * Output 69 | * 70 | * 60 71 | * 82.8 72 | */ 73 | ``` 74 | -------------------------------------------------------------------------------- /examples/module_metadata.md: -------------------------------------------------------------------------------- 1 | # Module Metadata 2 | 3 | ## Concepts 4 | 5 | - [import.meta](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta) 6 | can provide information on the context of the module. 7 | - The boolean [import.meta.main](/api?s=ImportMeta#prop_main) will let you know 8 | if the current module is the program entry point. 9 | - The string [import.meta.url](/api?s=ImportMeta#prop_url) will give you the URL 10 | of the current module. 11 | - The [import.meta.resolve](/api?s=ImportMeta#prop_resolve) allows you to 12 | resolve specifier relative to the current module. This function takes into 13 | account an import map (if one was provided on startup). 14 | - The string [Deno.mainModule](/api?s=Deno.mainModule) will give you the URL of 15 | the main module entry point, i.e. the module invoked by the deno runtime. 16 | 17 | ## Example 18 | 19 | The example below uses two modules to show the difference between 20 | `import.meta.url`, `import.meta.main` and `Deno.mainModule`. In this example, 21 | `module_a.ts` is the main module entry point: 22 | 23 | ```ts 24 | /** 25 | * module_b.ts 26 | */ 27 | export function outputB() { 28 | console.log("Module B's import.meta.url", import.meta.url); 29 | console.log("Module B's mainModule url", Deno.mainModule); 30 | console.log( 31 | "Is module B the main module via import.meta.main?", 32 | import.meta.main, 33 | ); 34 | } 35 | ``` 36 | 37 | ```ts, ignore 38 | /** 39 | * module_a.ts 40 | */ 41 | import { outputB } from "./module_b.ts"; 42 | 43 | function outputA() { 44 | console.log("Module A's import.meta.url", import.meta.url); 45 | console.log("Module A's mainModule url", Deno.mainModule); 46 | console.log( 47 | "Is module A the main module via import.meta.main?", 48 | import.meta.main, 49 | ); 50 | console.log( 51 | "Resolved specifier for ./module_b.ts", 52 | import.meta.resolve("./module_b.ts"), 53 | ); 54 | } 55 | 56 | outputA(); 57 | console.log(""); 58 | outputB(); 59 | ``` 60 | 61 | If `module_a.ts` is located in `/home/alice/deno` then the output of 62 | `deno run --allow-read module_a.ts` is: 63 | 64 | ``` 65 | Module A's import.meta.url file:///home/alice/deno/module_a.ts 66 | Module A's mainModule url file:///home/alice/deno/module_a.ts 67 | Is module A the main module via import.meta.main? true 68 | Resolved specifier for ./module_b.ts file:///home/alice/deno/module_b.ts 69 | 70 | Module B's import.meta.url file:///home/alice/deno/module_b.ts 71 | Module B's mainModule url file:///home/alice/deno/module_a.ts 72 | Is module B the main module via import.meta.main? false 73 | ``` 74 | -------------------------------------------------------------------------------- /examples/os_signals.md: -------------------------------------------------------------------------------- 1 | # Handle OS Signals 2 | 3 | > ⚠️ Windows only supports listening for SIGINT and SIGBREAK as of Deno v1.23. 4 | 5 | ## Concepts 6 | 7 | - [Deno.addSignalListener()](/api?s=Deno.addSignalListener) can be used to 8 | capture and monitor OS signals. 9 | - [Deno.removeSignalListener()](/api?s=Deno.removeSignalListener) can be used to 10 | stop watching the signal. 11 | 12 | ## Set up an OS signal listener 13 | 14 | APIs for handling OS signals are modelled after already familiar 15 | [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) 16 | and 17 | [`removeEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) 18 | APIs. 19 | 20 | > ⚠️ Note that listening for OS signals doesn't prevent event loop from 21 | > finishing, ie. if there are no more pending async operations the process will 22 | > exit. 23 | 24 | You can use `Deno.addSignalListener()` function for handling OS signals: 25 | 26 | ```ts 27 | /** 28 | * add_signal_listener.ts 29 | */ 30 | console.log("Press Ctrl-C to trigger a SIGINT signal"); 31 | 32 | Deno.addSignalListener("SIGINT", () => { 33 | console.log("interrupted!"); 34 | Deno.exit(); 35 | }); 36 | 37 | // Add a timeout to prevent process exiting immediately. 38 | setTimeout(() => {}, 5000); 39 | ``` 40 | 41 | Run with: 42 | 43 | ```shell 44 | deno run add_signal_listener.ts 45 | ``` 46 | 47 | You can use `Deno.removeSignalListener()` function to unregister previously 48 | added signal handler. 49 | 50 | ```ts 51 | /** 52 | * signal_listeners.ts 53 | */ 54 | console.log("Press Ctrl-C to trigger a SIGINT signal"); 55 | 56 | const sigIntHandler = () => { 57 | console.log("interrupted!"); 58 | Deno.exit(); 59 | }; 60 | Deno.addSignalListener("SIGINT", sigIntHandler); 61 | 62 | // Add a timeout to prevent process existing immediately. 63 | setTimeout(() => {}, 5000); 64 | 65 | // Stop listening for a signal after 1s. 66 | setTimeout(() => { 67 | Deno.removeSignalListener("SIGINT", sigIntHandler); 68 | }, 1000); 69 | ``` 70 | 71 | Run with: 72 | 73 | ```shell 74 | deno run signal_listeners.ts 75 | ``` 76 | 77 | ## Async iterator example 78 | 79 | If you prefer to handle signals using an async iterator, you can use 80 | [`signal()`](https://deno.land/std/signal/mod.ts) API available in `deno_std`: 81 | 82 | ```ts 83 | /** 84 | * async_iterator_signal.ts 85 | */ 86 | import { signal } from "https://deno.land/std@$STD_VERSION/signal/mod.ts"; 87 | 88 | const sig = signal("SIGUSR1", "SIGINT"); 89 | 90 | // Add a timeout to prevent process exiting immediately. 91 | setTimeout(() => {}, 5000); 92 | 93 | for await (const _ of sig) { 94 | console.log("interrupt or usr1 signal received"); 95 | } 96 | ``` 97 | 98 | Run with: 99 | 100 | ```shell 101 | deno run async_iterator_signal.ts 102 | ``` 103 | -------------------------------------------------------------------------------- /examples/read_write_files.md: -------------------------------------------------------------------------------- 1 | # Read and Write Files 2 | 3 | ## Concepts 4 | 5 | - Deno's runtime API provides the [Deno.readTextFile](/api?s=Deno.readTextFile) 6 | and [Deno.writeTextFile](/api?s=Deno.writeTextFile) asynchronous functions for 7 | reading and writing entire text files. 8 | - Like many of Deno's APIs, synchronous alternatives are also available. See 9 | [Deno.readTextFileSync](/api?s=Deno.readTextFileSync) and 10 | [Deno.writeTextFileSync](/api?s=Deno.writeTextFileSync). 11 | - Use `--allow-read` and `--allow-write` permissions to gain access to the file 12 | system. 13 | 14 | ## Overview 15 | 16 | Interacting with the filesystem to read and write files is a common requirement. 17 | Deno provides a number of ways to do this via the 18 | [standard library](https://deno.land/std) and the [Deno runtime API](/api). 19 | 20 | As highlighted in the [Fetch Data example](./fetch_data.md) Deno restricts 21 | access to Input / Output by default for security reasons. Therefore when 22 | interacting with the filesystem the `--allow-read` and `--allow-write` flags 23 | must be used with the `deno run` command. 24 | 25 | ## Reading a text file 26 | 27 | The Deno runtime API makes it possible to read text files via the 28 | `Deno.readTextFile()` method, it just requires a path string or URL object. The 29 | method returns a promise which provides access to the file's text data. 30 | 31 | **Command:** `deno run --allow-read read.ts` 32 | 33 | ```typescript 34 | /** 35 | * read.ts 36 | */ 37 | const text = await Deno.readTextFile("./people.json"); 38 | console.log(text); 39 | 40 | /** 41 | * Output: 42 | * 43 | * [ 44 | * {"id": 1, "name": "John", "age": 23}, 45 | * {"id": 2, "name": "Sandra", "age": 51}, 46 | * {"id": 5, "name": "Devika", "age": 11} 47 | * ] 48 | */ 49 | ``` 50 | 51 | ## Writing a text file 52 | 53 | The Deno runtime API allows developers to write text to files via the 54 | `Deno.writeTextFile()` method. It just requires a file path and text string. The 55 | method returns a promise which resolves when the file was successfully written. 56 | 57 | To run the command the `--allow-write` flag must be supplied to the `deno run` 58 | command. 59 | 60 | **Command:** `deno run --allow-write write.ts` 61 | 62 | ```typescript 63 | /** 64 | * write.ts 65 | */ 66 | await Deno.writeTextFile("./hello.txt", "Hello World!"); 67 | console.log("File written to ./hello.txt"); 68 | 69 | /** 70 | * Output: File written to ./hello.txt 71 | */ 72 | ``` 73 | 74 | You can _append_ text to a file like this: 75 | 76 | ```typescript 77 | await Deno.writeTextFile("./hello.txt", "This text will be appended.", { 78 | append: true, 79 | }); 80 | ``` 81 | 82 | By combining `Deno.writeTextFile` and `JSON.stringify` you can easily write 83 | serialized JSON objects to a file. This example uses synchronous 84 | `Deno.writeTextFileSync`, but this can also be done asynchronously using 85 | `await Deno.writeTextFile`. 86 | 87 | To execute the code the `deno run` command needs the write flag. 88 | 89 | **Command:** `deno run --allow-write write.ts` 90 | 91 | ```typescript 92 | /** 93 | * write.ts 94 | */ 95 | function writeJson(path: string, data: object): string { 96 | try { 97 | Deno.writeTextFileSync(path, JSON.stringify(data)); 98 | 99 | return "Written to " + path; 100 | } catch (e) { 101 | return e.message; 102 | } 103 | } 104 | 105 | console.log(writeJson("./data.json", { hello: "World" })); 106 | 107 | /** 108 | * Output: Written to ./data.json 109 | */ 110 | ``` 111 | -------------------------------------------------------------------------------- /examples/subprocess.md: -------------------------------------------------------------------------------- 1 | # Creating a Subprocess 2 | 3 | ## Concepts 4 | 5 | - Deno is capable of spawning a subprocess via 6 | [Deno.Command](/api?s=Deno.Command). 7 | - `--allow-run` permission is required to spawn a subprocess. 8 | - Spawned subprocesses do not run in a security sandbox. 9 | - Communicate with the subprocess via the [stdin](/api?s=Deno.stdin), 10 | [stdout](/api?s=Deno.stdout) and [stderr](/api?s=Deno.stderr) streams. 11 | 12 | ## Simple example 13 | 14 | This example is the equivalent of running `'echo hello'` from the command line. 15 | 16 | ```ts 17 | /** 18 | * subprocess_simple.ts 19 | */ 20 | 21 | // define command used to create the subprocess 22 | const command = new Deno.Command(Deno.execPath(), { 23 | args: [ 24 | "eval", 25 | "console.log('hello'); console.error('world')", 26 | ], 27 | }); 28 | 29 | // create subprocess and collect output 30 | const { code, stdout, stderr } = await command.output(); 31 | 32 | console.assert(code === 0); 33 | console.assert("world\n" === new TextDecoder().decode(stderr)); 34 | console.log(new TextDecoder().decode(stdout)); 35 | ``` 36 | 37 | Run it: 38 | 39 | ```shell 40 | $ deno run --allow-run --allow-read ./subprocess_simple.ts 41 | hello 42 | ``` 43 | 44 | ## Security 45 | 46 | The `--allow-run` permission is required for creation of a subprocess. Be aware 47 | that subprocesses are not run in a Deno sandbox and therefore have the same 48 | permissions as if you were to run the command from the command line yourself. 49 | 50 | ## Communicating with subprocesses 51 | 52 | By default when you use `Deno.Command()` the subprocess inherits `stdin`, 53 | `stdout` and `stderr` of the parent process. If you want to communicate with 54 | started a subprocess you must use the `"piped"` option. 55 | 56 | ## Piping to files 57 | 58 | This example is the equivalent of running `yes &> ./process_output` in bash. 59 | 60 | ```ts 61 | /** 62 | * subprocess_piping_to_file.ts 63 | */ 64 | 65 | import { mergeReadableStreams } from "https://deno.land/std@$STD_VERSION/streams/merge_readable_streams.ts"; 66 | 67 | // create the file to attach the process to 68 | const file = await Deno.open("./process_output.txt", { 69 | read: true, 70 | write: true, 71 | create: true, 72 | }); 73 | 74 | // start the process 75 | const command = new Deno.Command("yes", { 76 | stdout: "piped", 77 | stderr: "piped", 78 | }); 79 | 80 | const process = command.spawn(); 81 | 82 | // example of combining stdout and stderr while sending to a file 83 | const joined = mergeReadableStreams( 84 | process.stdout, 85 | process.stderr, 86 | ); 87 | 88 | // returns a promise that resolves when the process is killed/closed 89 | joined.pipeTo(file.writable).then(() => console.log("pipe join done")); 90 | 91 | // manually stop process "yes" will never end on its own 92 | setTimeout(() => { 93 | process.kill(); 94 | }, 100); 95 | ``` 96 | 97 | Run it: 98 | 99 | ```shell 100 | $ deno run --allow-run --allow-read --allow-write ./subprocess_piping_to_file.ts 101 | ``` 102 | -------------------------------------------------------------------------------- /examples/tcp_echo.md: -------------------------------------------------------------------------------- 1 | # TCP echo Server 2 | 3 | ## Concepts 4 | 5 | - Listening for TCP port connections with [Deno.listen](/api?s=Deno.listen). 6 | - Use [Deno.Conn.readable](/api?s=Deno.Conn#prop_readable) and 7 | [Deno.Conn.writable](/api?s=Deno.Conn#prop_writable) to take inbound data and 8 | redirect it to be outbound data. 9 | 10 | ## Example 11 | 12 | This is an example of a server which accepts connections on port 8080, and 13 | returns to the client anything it sends. 14 | 15 | ```ts 16 | /** 17 | * echo_server.ts 18 | */ 19 | const listener = Deno.listen({ port: 8080 }); 20 | console.log("listening on 0.0.0.0:8080"); 21 | for await (const conn of listener) { 22 | conn.readable.pipeTo(conn.writable); 23 | } 24 | ``` 25 | 26 | Run with: 27 | 28 | ```shell 29 | deno run --allow-net echo_server.ts 30 | ``` 31 | 32 | To test it, try sending data to it with 33 | [netcat](https://en.wikipedia.org/wiki/Netcat) (Linux/MacOS only). Below 34 | `'hello world'` is sent over the connection, which is then echoed back to the 35 | user: 36 | 37 | ```shell 38 | $ nc localhost 8080 39 | hello world 40 | hello world 41 | ``` 42 | 43 | Like the [cat.ts example](./unix_cat.md), the `pipeTo()` method here also does 44 | not make unnecessary memory copies. It receives a packet from the kernel and 45 | sends back, without further complexity. 46 | -------------------------------------------------------------------------------- /examples/tcp_server.md: -------------------------------------------------------------------------------- 1 | # TCP server 2 | 3 | This is an example of a server which accepts connections on port 8080, and 4 | returns to the client anything it sends. 5 | 6 | ```ts 7 | const hostname = "0.0.0.0"; 8 | const port = 8080; 9 | const listener = Deno.listen({ hostname, port }); 10 | console.log(`Listening on ${hostname}:${port}`); 11 | for await (const conn of listener) { 12 | conn.readable.pipeTo(conn.writable); 13 | } 14 | ``` 15 | 16 | For security reasons, Deno does not allow programs to access the network without 17 | explicit permission. To allow accessing the network, use a command-line flag: 18 | 19 | ```shell 20 | deno run --allow-net https://deno.land/std@0.198.0/examples/echo_server.ts 21 | ``` 22 | 23 | To test it, try sending data to it with `netcat` (or `telnet` on Windows): 24 | 25 | > Note for Windows users: netcat is not available on Windows. Instead you can 26 | > use the built-in telnet client. The telnet client is disabled in Windows by 27 | > default. It is easy to enable however: just follow the instructions 28 | > [on Microsoft TechNet](https://social.technet.microsoft.com/wiki/contents/articles/38433.windows-10-enabling-telnet-client.aspx) 29 | 30 | ```shell 31 | # Note for Windows users: replace the `nc` below with `telnet` 32 | $ nc localhost 8080 33 | hello world 34 | hello world 35 | ``` 36 | 37 | Like the `cat.ts` example, the `pipeTo(writable)` method does not make a copy of 38 | the data. The data is directly written from the readable stream to the writable 39 | stream. 40 | -------------------------------------------------------------------------------- /examples/unix_cat.md: -------------------------------------------------------------------------------- 1 | # An Implementation of the Unix "cat" Program 2 | 3 | ## Concepts 4 | 5 | - Use the Deno runtime API to output the contents of a file to the console. 6 | - [Deno.args](/api?s=Deno.args) accesses the command line arguments. 7 | - [Deno.open](/api?s=Deno.open) is used to get a handle to a file. 8 | - [Deno.stdout.writable](/api?s=Deno.stdout.writable) is used to get a writable 9 | stream to the console standard output. 10 | - [Deno.FsFile.readable](/api?s=Deno.FsFile#prop_readable) is used to get a 11 | readable stream from the file. (This readable stream closes the file when it 12 | is finished reading, so it is not necessary to close the file explicitly.) 13 | - Modules can be run directly from remote URLs. 14 | 15 | ## Example 16 | 17 | In this program each command-line argument is assumed to be a filename, the file 18 | is opened, and printed to stdout (e.g. the console). 19 | 20 | ```ts 21 | /** 22 | * cat.ts 23 | */ 24 | for (const filename of Deno.args) { 25 | const file = await Deno.open(filename); 26 | await file.readable.pipeTo(Deno.stdout.writable, { preventClose: true }); 27 | } 28 | ``` 29 | 30 | To run the program: 31 | 32 | ```shell 33 | deno run --allow-read https://deno.land/std@0.198.0/examples/cat.ts /etc/passwd 34 | ``` 35 | -------------------------------------------------------------------------------- /getting_started.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | In this chapter we'll discuss: 4 | 5 | - [Installing Deno](./getting_started/installation.md) 6 | - [Setting Up Your Environment](./getting_started/setup_your_environment.md) 7 | - [Running a `Hello World` Script](./getting_started/first_steps.md) 8 | - [Command Line Interface](./getting_started/command_line_interface.md) 9 | - [Configuration File](./getting_started/configuration_file.md) 10 | - [Web Frameworks](./getting_started/web_frameworks.md) 11 | -------------------------------------------------------------------------------- /getting_started/configuration_file.md: -------------------------------------------------------------------------------- 1 | # Configuration File 2 | 3 | Deno supports a configuration file that allows you to customize the built-in 4 | TypeScript compiler, formatter, and linter. 5 | 6 | The configuration file supports `.json` and `.jsonc` extensions. 7 | [Since v1.18](https://deno.com/blog/v1.18#auto-discovery-of-the-config-file), 8 | Deno will automatically detect a `deno.json` or `deno.jsonc` configuration file 9 | if it's in your current working directory or parent directories. The `--config` 10 | flag can be used to specify a different configuration file. 11 | 12 | > ⚠️ Before Deno v1.23 you needed to supply an explicit `--config` flag. 13 | 14 | > ⚠️ Starting with Deno v1.34 globs are supported in `include` and `exclude` 15 | > fields. You can use `*` to match any number of characters, `?` to match a 16 | > single character, and `**` to match any number of directories. 17 | 18 | ## `imports` and `scopes` 19 | 20 | Since version 1.30, the `deno.json` configuration file acts as an 21 | [import map](../basics/import_maps.md) for resolving bare specifiers. 22 | 23 | ```jsonc 24 | { 25 | "imports": { 26 | "std/": "https://deno.land/std@$STD_VERSION/" 27 | }, 28 | "tasks": { 29 | "dev": "deno run --watch main.ts" 30 | } 31 | } 32 | ``` 33 | 34 | See [the import map section](../basics/import_maps.md) for more information on 35 | import maps. 36 | 37 | Then your script can use the bare specifier `std`: 38 | 39 | ```js, ignore 40 | import { assertEquals } from "std/assert/mod.ts"; 41 | 42 | assertEquals(1, 2); 43 | ``` 44 | 45 | The top-level `deno.json` option `importMap` along with the `--importmap` flag 46 | can be used to specify the import map in other files. 47 | 48 | ## `tasks` 49 | 50 | Similar to `package.json`'s `script` field. Essentially shortcuts for command 51 | line invocations. 52 | 53 | ```json 54 | { 55 | "tasks": { 56 | "start": "deno run -A --watch=static/,routes/,data/ dev.ts" 57 | } 58 | } 59 | ``` 60 | 61 | Using `deno task start` will run the command. See also 62 | [`deno task`](../tools/task_runner.md). 63 | 64 | ## `lint` 65 | 66 | Configuration for [`deno lint`](../tools/linter.md). 67 | 68 | ```json 69 | { 70 | "lint": { 71 | "include": ["src/"], 72 | "exclude": ["src/testdata/", "data/fixtures/**/*.ts"], 73 | "rules": { 74 | "tags": ["recommended"], 75 | "include": ["ban-untagged-todo"], 76 | "exclude": ["no-unused-vars"] 77 | } 78 | } 79 | } 80 | ``` 81 | 82 | ## `fmt` 83 | 84 | Configuration for [`deno fmt`](../tools/formatter.md) 85 | 86 | ```json 87 | { 88 | "fmt": { 89 | "useTabs": true, 90 | "lineWidth": 80, 91 | "indentWidth": 4, 92 | "semiColons": true, 93 | "singleQuote": true, 94 | "proseWrap": "preserve", 95 | "include": ["src/"], 96 | "exclude": ["src/testdata/", "data/fixtures/**/*.ts"] 97 | } 98 | } 99 | ``` 100 | 101 | ## `lock` 102 | 103 | Used to specify a different file name for the lockfile. By default deno will use 104 | `deno.lock` and place it alongside the configuration file. 105 | 106 | ## `nodeModulesDir` 107 | 108 | Used to enable or disable the `node_modules` directory when using npm packages. 109 | 110 | ## `npmRegistry` 111 | 112 | Used to specify a custom npm registry for npm specifiers. 113 | 114 | ## `compilerOptions` 115 | 116 | `deno.json` can also act as a TypeScript configuration file and supports 117 | [most of the TS compiler options](https://www.typescriptlang.org/tsconfig). 118 | 119 | Deno encourages users to use the default TypeScript configuration to help 120 | sharing code. 121 | 122 | See also 123 | [Configuring TypeScript in Deno](../advanced/typescript/configuration.md). 124 | 125 | ## Full example 126 | 127 | ```json 128 | { 129 | "compilerOptions": { 130 | "allowJs": true, 131 | "lib": ["deno.window"], 132 | "strict": true 133 | }, 134 | "lint": { 135 | "include": ["src/"], 136 | "exclude": ["src/testdata/", "data/fixtures/**/*.ts"], 137 | "rules": { 138 | "tags": ["recommended"], 139 | "include": ["ban-untagged-todo"], 140 | "exclude": ["no-unused-vars"] 141 | } 142 | }, 143 | "fmt": { 144 | "useTabs": true, 145 | "lineWidth": 80, 146 | "indentWidth": 4, 147 | "semiColons": false, 148 | "singleQuote": true, 149 | "proseWrap": "preserve", 150 | "include": ["src/"], 151 | "exclude": ["src/testdata/", "data/fixtures/**/*.ts"] 152 | }, 153 | "lock": false, 154 | "nodeModulesDir": true, 155 | "npmRegistry": "https://mycompany.net/artifactory/api/npm/virtual-npm", 156 | "test": { 157 | "include": ["src/"], 158 | "exclude": ["src/testdata/", "data/fixtures/**/*.ts"] 159 | }, 160 | "tasks": { 161 | "start": "deno run --allow-read main.ts" 162 | }, 163 | "imports": { 164 | "oak": "https://deno.land/x/oak@v12.4.0/mod.ts" 165 | } 166 | } 167 | ``` 168 | 169 | ## JSON schema 170 | 171 | A JSON schema file is available for editors to provide autocompletion. The file 172 | is versioned and available at: 173 | https://deno.land/x/deno/cli/schemas/config-file.v1.json 174 | -------------------------------------------------------------------------------- /getting_started/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Deno works on macOS, Linux, and Windows. Deno is a single binary executable. It 4 | has no external dependencies. 5 | 6 | On macOS, both M1 (arm64) and Intel (x64) executables are provided. On Linux and 7 | Windows, only x64 is supported. 8 | 9 | ## Download and install 10 | 11 | [deno_install](https://github.com/denoland/deno_install) provides convenience 12 | scripts to download and install the binary. 13 | 14 | Using Shell (macOS and Linux): 15 | 16 | ```shell 17 | curl -fsSL https://deno.land/x/install/install.sh | sh 18 | ``` 19 | 20 | Using PowerShell (Windows): 21 | 22 | ```shell 23 | irm https://deno.land/install.ps1 | iex 24 | ``` 25 | 26 | Using [Winget](https://winget.run) (Windows): 27 | 28 | ```shell 29 | winget install --id DenoLand.Deno -e 30 | ``` 31 | 32 | Using [Scoop](https://scoop.sh/) (Windows): 33 | 34 | ```shell 35 | scoop install deno 36 | ``` 37 | 38 | Using [Chocolatey](https://chocolatey.org/packages/deno) (Windows): 39 | 40 | ```shell 41 | choco install deno 42 | ``` 43 | 44 | Using [Homebrew](https://formulae.brew.sh/formula/deno) (macOS): 45 | 46 | ```shell 47 | brew install deno 48 | ``` 49 | 50 | Using [MacPorts](https://ports.macports.org/port/deno/) (macOS): 51 | 52 | ```shell 53 | sudo port install deno 54 | ``` 55 | 56 | Using [Nix](https://nixos.org/download.html) (macOS and Linux): 57 | 58 | ```shell 59 | nix-shell -p deno 60 | ``` 61 | 62 | Using [asdf](https://asdf-vm.com/) (macOS and Linux): 63 | 64 | ```shell 65 | asdf plugin-add deno https://github.com/asdf-community/asdf-deno.git 66 | asdf install deno latest 67 | 68 | # To install globally 69 | asdf global deno latest 70 | 71 | # To install locally (current project only) 72 | asdf local deno latest 73 | ``` 74 | 75 | Build and install from source using [Cargo](https://crates.io/crates/deno): 76 | 77 | ```shell 78 | cargo install deno --locked 79 | ``` 80 | 81 | Deno binaries can also be installed manually, by downloading a zip file at 82 | [github.com/denoland/deno/releases](https://github.com/denoland/deno/releases). 83 | These packages contain just a single executable file. You will have to set the 84 | executable bit on macOS and Linux. 85 | 86 | ## Docker 87 | 88 | For more information and instructions on the official Docker images: 89 | [https://github.com/denoland/deno_docker](https://github.com/denoland/deno_docker) 90 | 91 | ## Testing your installation 92 | 93 | To test your installation, run `deno --version`. If this prints the Deno version 94 | to the console the installation was successful. 95 | 96 | Use `deno help` to see help text documenting Deno's flags and usage. Get a 97 | detailed guide on the CLI [here](./command_line_interface.md). 98 | 99 | ## Updating 100 | 101 | To update a previously installed version of Deno, you can run: 102 | 103 | ```shell 104 | deno upgrade 105 | ``` 106 | 107 | Or using [Winget](https://winget.run) (Windows): 108 | 109 | ```shell 110 | winget upgrade --id DenoLand.Deno -e 111 | ``` 112 | 113 | This will fetch the latest release from 114 | [github.com/denoland/deno/releases](https://github.com/denoland/deno/releases), 115 | unzip it, and replace your current executable with it. 116 | 117 | You can also use this utility to install a specific version of Deno: 118 | 119 | ```shell 120 | deno upgrade --version 1.0.1 121 | ``` 122 | 123 | ## Building from source 124 | 125 | Information about how to build from source can be found in the 126 | [`Contributing`](../references/contributing/building_from_source.md) chapter. 127 | -------------------------------------------------------------------------------- /getting_started/typescript.md: -------------------------------------------------------------------------------- 1 | # Using TypeScript 2 | 3 | > ℹ️ This section has been moved to 4 | > [Using TypeScript Chapter](../advanced/typescript.md). 5 | -------------------------------------------------------------------------------- /getting_started/web_frameworks.md: -------------------------------------------------------------------------------- 1 | # Web Frameworks 2 | 3 | Most likely, if you're building a more complex application, you'll be 4 | interacting with Deno through a web framework. There are two kinds of web 5 | frameworks that Deno supports: 6 | 7 | - **Node.js native frameworks/tools/libraries.** Some of the most popular 8 | tooling, for example esbuild, explicitly supports both Node.js and Deno. The 9 | drawback here is that you might not get the best experience or performance. 10 | - **Deno native frameworks/tools/libraries.** We present some of these below. 11 | 12 | ## Deno-native frameworks 13 | 14 | ### Fresh 15 | 16 | [Fresh](https://fresh.deno.dev/) is the most popular web framework for Deno. It 17 | uses a model where you send no JavaScript to clients by default. The majority of 18 | rendering is done on a server, and the client is only responsible for 19 | re-rendering small 20 | [islands of interactivity](https://jasonformat.com/islands-architecture/). This 21 | means the developer explicitly opts in to client side rendering for specific 22 | components. 23 | 24 | ### Aleph 25 | 26 | [Aleph.js](https://alephjs.org/docs/get-started) is the second most popular web 27 | framework for Deno. It gives you the same sort of quick-start with React as 28 | Create-React-App. Like Next.js, Aleph provides SSR and SSG out of the box in 29 | order to allow developers to create SEO-friendly apps. In addition, Aleph 30 | provides some other built-in features that don't come out of the box in Next.js, 31 | such as: 32 | 33 | - Hot Reloading (Using React Fast Refresh) 34 | - ESM Import Syntax (No need for webpack) 35 | - TypeScript-Readys 36 | 37 | ### Ultra 38 | 39 | [Ultra](https://ultrajs.dev/) is a modern streaming React framework for Deno 40 | that is another alternative to Aleph. It's a way to use React to build dynamic 41 | media-rich websites, similar to Next.js. 42 | 43 | Deno itself supports JSX and TypeScript out-of-the-box (and therefore Ultra does 44 | as well), but they don't work in the browser. Ultra takes over the task of 45 | transpiling JSX and TypeScript to regular JavaScript. 46 | 47 | Other highlights of Ultra include: 48 | 49 | - written in Deno. 50 | - powered by import maps. 51 | - 100% esm. 52 | - uses import maps in both development and production, which massively 53 | simplifies toolchains - you don't have to deal with heaps of bundling and 54 | transpilation. 55 | - source code is shipped in production, similar to how it's written. 56 | - imports, exports, work as they do in development. 57 | 58 | ### Lume 59 | 60 | [Lume](https://lume.land/) is a static site generator for Deno that is inspired 61 | by other static site generators such Jekyll or Eleventy. It's simple to use and 62 | configure, while being super flexible. Highlights include: 63 | 64 | - Support for multiple file formats like Markdown, YAML, JavaScript, TypeScript, 65 | JSX, Nunjucks. 66 | - You can hook in any processor to transform assets, for example sass or postcss 67 | for CSS. 68 | - No need to install thousand of packages in `node_modules` or complex bundlers. 69 | 70 | ### Oak 71 | 72 | [Oak](https://deno.land/x/oak) is a web application framework for Deno, similar 73 | to Express in Node.js. 74 | 75 | As a middleware framework, Oak is the glue between your frontend application and 76 | a potential database or other data sources (e.g. REST APIs, GraphQL APIs). Just 77 | to give you an idea, the following is a list of common tech stacks to build 78 | client-server architectures: 79 | 80 | - React.js (Frontend) + Oak (Backend) + PostgreSQL (Database) 81 | - Vue.js (Frontend) + Oak (Backend) + MongoDB (Database) 82 | - Angular.js (Frontend) + Oak (Backend) + Neo4j (Database) 83 | 84 | Oak offers additional functionality over the native Deno HTTP server, including 85 | a basic router, JSON parser, middlewares, plugins, etc. 86 | -------------------------------------------------------------------------------- /help.md: -------------------------------------------------------------------------------- 1 | # Where To Get Help 2 | 3 | Stuck? Lost? Get Help from the Community. 4 | 5 | ## [Community Discord](https://discord.gg/deno) 6 | 7 | Ask questions and chat with community members in real-time. 8 | 9 | ## [Stack Overflow](https://stackoverflow.com/questions/tagged/deno) 10 | 11 | Stack Overflow is a popular forum to ask code-level questions or if you're stuck 12 | with a specific error. 13 | [ask your own!](https://stackoverflow.com/questions/ask?tags=deno) 14 | 15 | ## [DEV's Deno Community](https://dev.to/t/deno) 16 | 17 | A great place to find interesting articles about best practices, application 18 | architecture and new learnings. Post your articles with the tag `deno`. 19 | -------------------------------------------------------------------------------- /images/chat_app_render.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/chat_app_render.png -------------------------------------------------------------------------------- /images/debugger1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/debugger1.jpg -------------------------------------------------------------------------------- /images/debugger2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/debugger2.jpg -------------------------------------------------------------------------------- /images/debugger3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/debugger3.jpg -------------------------------------------------------------------------------- /images/debugger4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/debugger4.jpg -------------------------------------------------------------------------------- /images/debugger5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/debugger5.jpg -------------------------------------------------------------------------------- /images/debugger7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/debugger7.jpg -------------------------------------------------------------------------------- /images/deno3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/deno3.png -------------------------------------------------------------------------------- /images/how-to/aws-lightsail/create-container-service-on-aws.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/aws-lightsail/create-container-service-on-aws.png -------------------------------------------------------------------------------- /images/how-to/aws-lightsail/hello-world-from-deno-and-aws-lightsail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/aws-lightsail/hello-world-from-deno-and-aws-lightsail.png -------------------------------------------------------------------------------- /images/how-to/aws-lightsail/hello-world-from-localhost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/aws-lightsail/hello-world-from-localhost.png -------------------------------------------------------------------------------- /images/how-to/aws-lightsail/new-image-on-docker-hub.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/aws-lightsail/new-image-on-docker-hub.png -------------------------------------------------------------------------------- /images/how-to/cloudflare-workers/main-on-cloudflare.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/cloudflare-workers/main-on-cloudflare.png -------------------------------------------------------------------------------- /images/how-to/digital-ocean/hello-from-deno-and-digital-ocean.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/digital-ocean/hello-from-deno-and-digital-ocean.png -------------------------------------------------------------------------------- /images/how-to/digital-ocean/hello-world-from-localhost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/digital-ocean/hello-world-from-localhost.png -------------------------------------------------------------------------------- /images/how-to/digital-ocean/new-deno-image-on-digital-ocean-container-registry.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/digital-ocean/new-deno-image-on-digital-ocean-container-registry.png -------------------------------------------------------------------------------- /images/how-to/google-cloud-run/hello-from-google-cloud-run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/google-cloud-run/hello-from-google-cloud-run.png -------------------------------------------------------------------------------- /images/how-to/google-cloud-run/hello-world-from-localhost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/google-cloud-run/hello-world-from-localhost.png -------------------------------------------------------------------------------- /images/how-to/google-cloud-run/image-in-google-artifact-registry.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/google-cloud-run/image-in-google-artifact-registry.png -------------------------------------------------------------------------------- /images/how-to/google-cloud-run/new-repository-in-google-artifact-repository.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/google-cloud-run/new-repository-in-google-artifact-repository.png -------------------------------------------------------------------------------- /images/how-to/prisma/1-dinosaurs-in-prisma.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/prisma/1-dinosaurs-in-prisma.png -------------------------------------------------------------------------------- /images/how-to/prisma/2-dinosaurs-from-api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/prisma/2-dinosaurs-from-api.png -------------------------------------------------------------------------------- /images/how-to/prisma/3-new-dinosaur-in-prisma.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/prisma/3-new-dinosaur-in-prisma.png -------------------------------------------------------------------------------- /images/how-to/react/dinosaur-api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/react/dinosaur-api.png -------------------------------------------------------------------------------- /images/how-to/react/react-dinosaur-app-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/react/react-dinosaur-app-demo.gif -------------------------------------------------------------------------------- /images/how-to/redis/cached-redis-body.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/redis/cached-redis-body.png -------------------------------------------------------------------------------- /images/how-to/redis/cached-redis-header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/redis/cached-redis-header.png -------------------------------------------------------------------------------- /images/how-to/redis/uncached-redis-body.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/redis/uncached-redis-body.png -------------------------------------------------------------------------------- /images/how-to/redis/uncached-redis-header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/redis/uncached-redis-header.png -------------------------------------------------------------------------------- /images/how-to/vue/api-response.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/vue/api-response.png -------------------------------------------------------------------------------- /images/how-to/vue/default-vue-app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/vue/default-vue-app.png -------------------------------------------------------------------------------- /images/how-to/vue/vue-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/how-to/vue/vue-demo.gif -------------------------------------------------------------------------------- /images/jb-ide-debug.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/jb-ide-debug.png -------------------------------------------------------------------------------- /images/node_modules_dir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/node_modules_dir.png -------------------------------------------------------------------------------- /images/private-github-new-token.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/private-github-new-token.png -------------------------------------------------------------------------------- /images/private-github-token-display.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/private-github-token-display.png -------------------------------------------------------------------------------- /images/private-pat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/private-pat.png -------------------------------------------------------------------------------- /images/word_finder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/word_finder.png -------------------------------------------------------------------------------- /images/workspace_folder_config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/denoland/manual/1eb97b229db72a0e906a0ecd4fb2600fe1843581/images/workspace_folder_config.png -------------------------------------------------------------------------------- /introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Deno ([/ˈdiːnoʊ/](http://ipa-reader.xyz/?text=%CB%88di%CB%90no%CA%8A), 4 | pronounced `dee-no`) is a JavaScript, TypeScript, and WebAssembly runtime with 5 | secure defaults and a great developer experience. 6 | 7 | It's built on V8, Rust, and Tokio. 8 | 9 | ## Feature highlights 10 | 11 | - Provides [web platform functionality](./runtime/web_platform_apis.md) and 12 | adopts web platform standards. For example using ES modules, web workers, and 13 | support `fetch()`. 14 | - [Secure by default](./basics/permissions.md). No file, network, or environment 15 | access unless explicitly enabled. 16 | - Supports [TypeScript](./advanced/typescript.md) out of the box. 17 | - Ships a single executable (`deno`). 18 | - Provides built-in [development tooling](./tools.md) like a code formatter 19 | ([`deno fmt`](./tools/formatter.md)), a linter 20 | ([`deno lint`](./tools/linter.md)), a test runner 21 | ([`deno test`](./basics/testing.md)), and a 22 | [language server for your editor](./getting_started/setup_your_environment.md#using-an-editoride). 23 | - Has 24 | [a set of reviewed (audited) standard modules](https://deno.land/std@$STD_VERSION) 25 | that are guaranteed to work with Deno. 26 | - Supports the use of [existing npm modules](./node.md) 27 | 28 | ## Philosophy 29 | 30 | Deno aims to be a productive, secure, and performant runtime for the modern 31 | programmer. 32 | 33 | Deno will always be distributed as a single executable. Given a URL to a Deno 34 | program, it is runnable with nothing more than 35 | [the ~31 megabyte zipped executable](https://github.com/denoland/deno/releases). 36 | Deno explicitly takes on the role of both runtime and package manager. It uses a 37 | standard browser-compatible protocol for loading modules: URLs. 38 | 39 | Among other things, Deno is a great replacement for utility scripts that may 40 | have been historically written with Bash or Python. 41 | 42 | ## Goals 43 | 44 | - Ship as just a single executable (`deno`). 45 | - Provide secure defaults. 46 | - Unless specifically allowed, scripts can't access files, the environment, or 47 | the network. 48 | - Be browser-compatible. 49 | - The subset of Deno programs which are written completely in JavaScript and 50 | do not use the global `Deno` namespace (or feature test for it), ought to 51 | also be able to be run in a modern web browser without change. 52 | - Provide built-in tooling to improve developer experience. 53 | - E.g. unit testing, code formatting, and linting. 54 | - Keep V8 concepts out of user land. 55 | - Serve HTTP efficiently. 56 | 57 | ## Other key behaviors 58 | 59 | - Fetch and cache remote code upon first execution, and never update it until 60 | the code is run with the `--reload` flag. (So, this will still work on an 61 | airplane.) 62 | - Modules/files loaded from remote URLs are intended to be immutable and 63 | cacheable. 64 | -------------------------------------------------------------------------------- /node.md: -------------------------------------------------------------------------------- 1 | # Node and npm modules 2 | 3 | Many people will want to leverage code and libraries that are built for 4 | [Node](https://nodejs.org/), in particular the large set of packages available 5 | on the [npm](https://npmjs.com/) registry. 6 | 7 | There are currently several ways to do this: 8 | 9 | - Using [`npm:` specifiers](./node/npm_specifiers.md) and 10 | [`node:` specifiers](./node/node_specifiers.md) 11 | - [package.json compatibility](./node/package_json.md) 12 | - Using [CDNs](./node/cdns.md) 13 | -------------------------------------------------------------------------------- /node/cdns.md: -------------------------------------------------------------------------------- 1 | # npm via CDNs 2 | 3 | Most developers currently use npm modules in Deno by importing them using one of 4 | many CDNs. You can reference the CDN URL in your Deno code or directly in your 5 | browser as an ES Module. These CDN URLs are reusable - they also provide 6 | instructions on how to be used in Deno, the browser, etc. 7 | 8 | **Starting with Deno release 1.28**, Deno also offers stabilized support for 9 | [`npm:` specifiers](./npm_specifiers.md), which are a new way of using npm 10 | modules in Deno. 11 | 12 | **Starting with Deno release 1.31**, Deno supports resolving npm dependencies 13 | [from package.json](./package_json.md) if it exists. 14 | 15 | ### esm.sh 16 | 17 | [esm.sh](https://esm.sh/) is a CDN that was specifically designed for Deno, 18 | though addressing the concerns for Deno also makes it a general purpose CDN for 19 | accessing npm packages as ES Module bundles. esm.sh uses 20 | [esbuild](https://esbuild.github.io/) to take an arbitrary npm package and 21 | ensure that it is consumable as an ES Module. In many cases you can just import 22 | the npm package into your Deno application: 23 | 24 | ```tsx 25 | import React from "https://esm.sh/react"; 26 | 27 | export default class A extends React.Component { 28 | render() { 29 | return
; 30 | } 31 | } 32 | ``` 33 | 34 | esm.sh supports the use of both specific versions of packages, as well as 35 | [semver](https://semver.npmjs.com/) versions of packages, so you can express 36 | your dependency in a similar way you would in a `package.json` file when you 37 | import it. For example, to get a specific version of a package: 38 | 39 | ```tsx 40 | import React from "https://esm.sh/react@17.0.2"; 41 | ``` 42 | 43 | Or to get the latest patch release of a minor release: 44 | 45 | ```tsx 46 | import React from "https://esm.sh/react@~16.13.0"; 47 | ``` 48 | 49 | Or to get a submodule: 50 | 51 | ```tsx 52 | import { renderToString } from "https://esm.sh/react-dom/server"; 53 | ``` 54 | 55 | Or to import regular files: 56 | 57 | ```tsx, ignore 58 | import "https://esm.sh/tailwindcss/dist/tailwind.min.css"; 59 | ``` 60 | 61 | esm.sh also automatically sets a header which Deno recognizes that allows Deno 62 | to be able to retrieve type definitions for the package/module. See 63 | [Using `X-TypeScript-Types` header](../advanced/typescript/types.md#using-x-typescript-types-header) 64 | in this manual for more details on how this works. 65 | 66 | esm.sh also provides information on 67 | [self hosting the CDN](https://github.com/ije/esm.sh/blob/main/HOSTING.md). 68 | 69 | Check out the [esm.sh homepage](https://esm.sh/) for more detailed information 70 | on how the CDN can be used and what features it has. 71 | 72 | ### UNPKG 73 | 74 | [UNPKG](https://unpkg.com/) is the most well known CDN for npm packages. For 75 | packages that include an ES Module distribution for things like the browsers, 76 | many of them can be used directly off of UNPKG. That being said, everything 77 | available on UNPKG is available on more Deno friendly CDNs. 78 | 79 | ### JSPM 80 | 81 | The [jspm.io](https://jspm.io) CDN is specifically designed to provide npm and 82 | other registry packages as ES Modules in a way that works well with import maps. 83 | While it doesn't currently cater to Deno, the fact that Deno can utilize import 84 | maps, allows you to use the [JSPM.io generator](https://generator.jspm.io/) to 85 | generate an import-map of all the packages you want to use and have them served 86 | up from the CDN. 87 | -------------------------------------------------------------------------------- /node/faqs.md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Questions 2 | 3 | ## Getting type errors like cannot find `document` or `HTMLElement` 4 | 5 | The library you are using has dependencies on the DOM. This is common for 6 | packages that are designed to run in a browser as well as server-side. By 7 | default, Deno only includes the libraries that are directly supported. Assuming 8 | the package properly identifies what environment it is running in at runtime it 9 | is "safe" to use the DOM libraries to type check the code. For more information 10 | on this, check out the 11 | [Targeting Deno and the Browser](../advanced/typescript/configuration.md#targeting-deno-and-the-browser) 12 | section of the manual. 13 | -------------------------------------------------------------------------------- /node/how_to_with_npm.md: -------------------------------------------------------------------------------- 1 | # How To guides with npm 2 | 3 | Here's a collection of How To guides to help you get started using a particular 4 | npm module with Deno. 5 | 6 | ## Data Persistence 7 | 8 | - [Prisma](how_to_with_npm/prisma.md) 9 | - [Mongoose](how_to_with_npm/mongoose.md) 10 | - [MySQL2](how_to_with_npm/mysql2.md) 11 | - [Redis](how_to_with_npm/redis.md) 12 | - [Apollo](how_to_with_npm/apollo.md) 13 | - [PlanetScale](how_to_with_npm/planetscale.md) 14 | 15 | ## Frameworks 16 | 17 | - [React](how_to_with_npm/react.md) 18 | - [Vue](how_to_with_npm/vue.md) 19 | - [Express](how_to_with_npm/express.md) 20 | -------------------------------------------------------------------------------- /node/how_to_with_npm/express.md: -------------------------------------------------------------------------------- 1 | # How to use Express with Deno 2 | 3 | [Express](https://expressjs.com/) is a popular web framework known for being 4 | simple and unopinionated with a large ecosystem of middleware. 5 | 6 | This How To guide will show you how to create a simple API using Express and 7 | Deno. 8 | 9 | [View source here.](https://github.com/denoland/examples/tree/main/with-express) 10 | 11 | ## Create `main.ts` 12 | 13 | Let's create `main.ts`: 14 | 15 | ``` 16 | touch main.ts 17 | ``` 18 | 19 | In `main.ts`, let's create a simple server: 20 | 21 | ```ts, ignore 22 | // @deno-types="npm:@types/express@4.17.15" 23 | import express from "npm:express@4.18.2"; 24 | 25 | const app = express(); 26 | 27 | app.get("/", (req, res) => { 28 | res.send("Welcome to the Dinosaur API!"); 29 | }); 30 | 31 | app.listen(8000); 32 | ``` 33 | 34 | Let's run this server: 35 | 36 | ``` 37 | deno run -A main.ts 38 | ``` 39 | 40 | And point our browser to `localhost:8000`. You should see: 41 | 42 | ``` 43 | Welcome to the Dinosaur API! 44 | ``` 45 | 46 | ## Add data and routes 47 | 48 | The next step here is to add some data. We'll use this Dinosaur data that we 49 | found from [this article](https://www.thoughtco.com/dinosaurs-a-to-z-1093748). 50 | Feel free to 51 | [copy it from here](https://github.com/denoland/examples/blob/main/with-express/data.json). 52 | 53 | Let's create `data.json`: 54 | 55 | ``` 56 | touch data.json 57 | ``` 58 | 59 | And paste in the dinosaur data. 60 | 61 | Next, let's import that data into `main.ts`. Let's add this line at the top of 62 | the file: 63 | 64 | ```ts, ignore 65 | import data from "./data.json" assert { type: "json" }; 66 | ``` 67 | 68 | Then, we can create the routes to access that data. To keep it simple, let's 69 | just define `GET` handlers for `/api/` and `/api/:dinosaur`. Add the below after 70 | the `const app = express();` line: 71 | 72 | ```ts, ignore 73 | app.get("/", (req, res) => { 74 | res.send("Welcome to the Dinosaur API!"); 75 | }); 76 | 77 | app.get("/api", (req, res) => { 78 | res.send(data); 79 | }); 80 | 81 | app.get("/api/:dinosaur", (req, res) => { 82 | if (req?.params?.dinosaur) { 83 | const found = data.find((item) => 84 | item.name.toLowerCase() === req.params.dinosaur.toLowerCase() 85 | ); 86 | if (found) { 87 | res.send(found); 88 | } else { 89 | res.send("No dinosaurs found."); 90 | } 91 | } 92 | }); 93 | 94 | app.listen(8000); 95 | ``` 96 | 97 | Let's run the server with `deno run -A main.ts` and check out 98 | `localhost:8000/api`. You should see a list of dinosaurs: 99 | 100 | ```json, ignore 101 | [ 102 | { 103 | "name": "Aardonyx", 104 | "description": "An early stage in the evolution of sauropods." 105 | }, 106 | { 107 | "name": "Abelisaurus", 108 | "description": "\"Abel's lizard\" has been reconstructed from a single skull." 109 | }, 110 | { 111 | "name": "Abrictosaurus", 112 | "description": "An early relative of Heterodontosaurus." 113 | }, 114 | ... 115 | ``` 116 | 117 | And when we go to `localhost:8000/api/aardonyx`: 118 | 119 | ```json, ignore 120 | { 121 | "name": "Aardonyx", 122 | "description": "An early stage in the evolution of sauropods." 123 | } 124 | ``` 125 | 126 | Great! 127 | -------------------------------------------------------------------------------- /node/how_to_with_npm/mongoose.md: -------------------------------------------------------------------------------- 1 | # How to use Mongoose with Deno 2 | 3 | [Mongoose](https://mongoosejs.com/) is a popular, schema-based library that 4 | models data for [MongoDB](https://www.mongodb.com/). It simplifies writing 5 | MongoDB validation, casting, and other relevant business logic. 6 | 7 | This tutorial will show you how to setup Mongoose and MongoDB with your Deno 8 | project. 9 | 10 | [View source](https://github.com/denoland/examples/tree/main/with-mongoose) or 11 | [check out the video guide](https://youtu.be/dmZ9Ih0CR9g). 12 | 13 | ## Creating a Mongoose Model 14 | 15 | Let's create a simple app that connects to MongoDB, creates a `Dinosaur` model, 16 | and adds and updates a dinosaur to the database. 17 | 18 | First, we'll create the necessary files and directories: 19 | 20 | ``` 21 | $ touch main.ts && mkdir model && touch model/Dinosaur.ts 22 | ``` 23 | 24 | In `/model/Dinosaur.ts`, we'll import `npm:mongoose`, define the [schema], and 25 | export it: 26 | 27 | ```ts, ignore 28 | import { model, Schema } from "npm:mongoose@^6.7"; 29 | 30 | // Define schema. 31 | const dinosaurSchema = new Schema({ 32 | name: { type: String, unique: true }, 33 | description: String, 34 | createdAt: { type: Date, default: Date.now }, 35 | updatedAt: { type: Date, default: Date.now }, 36 | }); 37 | 38 | // Validations 39 | dinosaurSchema.path("name").required(true, "Dinosaur name cannot be blank."); 40 | dinosaurSchema.path("description").required( 41 | true, 42 | "Dinosaur description cannot be blank.", 43 | ); 44 | 45 | // Export model. 46 | export default model("Dinosaur", dinosaurSchema); 47 | ``` 48 | 49 | ## Connecting to MongoDB 50 | 51 | Now, in our `main.ts` file, we'll import mongoose and the `Dinosaur` schema, and 52 | connect to MongoDB: 53 | 54 | ```ts, ignore 55 | import mongoose from "npm:mongoose@^6.7"; 56 | import Dinosaur from "./model/Dinosaur.ts"; 57 | 58 | await mongoose.connect("mongodb://localhost:27017"); 59 | 60 | // Check to see connection status. 61 | console.log(mongoose.connection.readyState); 62 | ``` 63 | 64 | Because Deno supports top-level `await`, we're able to simply 65 | `await mongoose.connect()`. 66 | 67 | Running this, we should expect a log of `1`: 68 | 69 | ```shell, ignore 70 | $ deno run --allow-read --allow-sys --allow-env --allow-net main.ts 71 | 1 72 | ``` 73 | 74 | It worked! 75 | 76 | ## Manipulating Data 77 | 78 | Let's add an instance [method](https://mongoosejs.com/docs/guide.html#methods) 79 | to our `Dinosaur` schema in `/model/Dinosaur.ts`: 80 | 81 | ```ts, ignore 82 | // ./model/Dinosaur.ts 83 | 84 | // Methods. 85 | dinosaurSchema.methods = { 86 | // Update description. 87 | updateDescription: async function (description: string) { 88 | this.description = description; 89 | return await this.save(); 90 | }, 91 | }; 92 | 93 | // ... 94 | ``` 95 | 96 | This instance method, `updateDescription`, will allow you to update a record's 97 | description. 98 | 99 | Back in `main.ts`, let's start adding and manipulating data in MongoDB. 100 | 101 | ```ts, ignore 102 | // main.ts 103 | 104 | // Create a new Dinosaur. 105 | const deno = new Dinosaur({ 106 | name: "Deno", 107 | description: "The fastest dinosaur ever lived.", 108 | }); 109 | 110 | // // Insert deno. 111 | await deno.save(); 112 | 113 | // Find Deno by name. 114 | const denoFromMongoDb = await Dinosaur.findOne({ name: "Deno" }); 115 | console.log( 116 | `Finding Deno in MongoDB -- \n ${denoFromMongoDb.name}: ${denoFromMongoDb.description}`, 117 | ); 118 | 119 | // Update description for Deno and save it. 120 | await denoFromMongoDb.updateDescription( 121 | "The fastest and most secure dinosaur ever lived.", 122 | ); 123 | 124 | // Check MongoDB to see Deno's updated description. 125 | const newDenoFromMongoDb = await Dinosaur.findOne({ name: "Deno" }); 126 | console.log( 127 | `Finding Deno (again) -- \n ${newDenoFromMongoDb.name}: ${newDenoFromMongoDb.description}`, 128 | ); 129 | ``` 130 | 131 | Running the code, we get: 132 | 133 | ``` 134 | Finding Deno in MongoDB -- 135 | Deno: The fastest dinosaur ever lived. 136 | Finding Deno (again) -- 137 | Deno: The fastest and most secure dinosaur ever lived. 138 | ``` 139 | 140 | Boom! 141 | 142 | For more info on using Mongoose, please refer to 143 | [their documentation](https://mongoosejs.com/docs/guide.html). 144 | -------------------------------------------------------------------------------- /node/how_to_with_npm/mysql2.md: -------------------------------------------------------------------------------- 1 | # How to use MySQL2 with Deno 2 | 3 | [MySQL](https://www.mysql.com/) is the most popular database in the 4 | [2022 Stack Overflow Developer Survey](https://survey.stackoverflow.co/2022/#most-popular-technologies-database) 5 | and counts Facebook, Twitter, YouTube, and Netflix among its users. 6 | 7 | [View source here.](https://github.com/denoland/examples/tree/main/with-mysql2) 8 | 9 | You can manipulate and query a MySQL database with Deno using the `mysql2` node 10 | package and importing via `npm:mysql2`. This allows us to use its Promise 11 | wrapper and take advantage of top-level await. 12 | 13 | ```tsx, ignore 14 | import mysql from "npm:mysql2@^2.3.3/promise"; 15 | ``` 16 | 17 | ## Connecting to MySQL 18 | 19 | We can connect to our MySQL server using the `createConnection()` method. You 20 | need the host (`localhost` if you are testing, or more likely a cloud database 21 | endpoint in production) and the user and password: 22 | 23 | ```tsx, ignore 24 | const connection = await mysql.createConnection({ 25 | host: "localhost", 26 | user: "root", 27 | password: "password", 28 | }); 29 | ``` 30 | 31 | You can also optionally specify a database during the connection creation. Here 32 | we are going to use `mysql2` to create the database on the fly. 33 | 34 | ## Creating and populating the database 35 | 36 | Now that you have the connection running, you can use `connection.query()` with 37 | SQL commands to create databases and tables as well as insert the initial data. 38 | 39 | First we want to generate and select the database to use: 40 | 41 | ```tsx, ignore 42 | await connection.query("CREATE DATABASE denos"); 43 | await connection.query("use denos"); 44 | ``` 45 | 46 | Then we want to create the table: 47 | 48 | ```tsx, ignore 49 | await connection.query( 50 | "CREATE TABLE `dinosaurs` ( `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) NOT NULL, `description` varchar(255) )", 51 | ); 52 | ``` 53 | 54 | After the table is created we can populate the data: 55 | 56 | ```tsx, ignore 57 | await connection.query( 58 | "INSERT INTO `dinosaurs` (id, name, description) VALUES (1, 'Aardonyx', 'An early stage in the evolution of sauropods.'), (2, 'Abelisaurus', 'Abels lizard has been reconstructed from a single skull.'), (3, 'Deno', 'The fastest dinosaur that ever lived.')", 59 | ); 60 | ``` 61 | 62 | We now have all the data ready to start querying. 63 | 64 | ## Querying MySQL 65 | 66 | We can use the same connection.query() method to write our queries. First we try 67 | and get all the data in our `dinosaurs` table: 68 | 69 | ```tsx, ignore 70 | const results = await connection.query("SELECT * FROM `dinosaurs`"); 71 | console.log(results); 72 | ``` 73 | 74 | The result from this query is all the data in our database: 75 | 76 | ```tsx, ignore 77 | [ 78 | [ 79 | { 80 | id: 1, 81 | name: "Aardonyx", 82 | description: "An early stage in the evolution of sauropods." 83 | }, 84 | { 85 | id: 2, 86 | name: "Abelisaurus", 87 | description: `Abel's lizard" has been reconstructed from a single skull.` 88 | }, 89 | { id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." } 90 | ], 91 | ``` 92 | 93 | If we want to just get a single element from the database, we can change our 94 | query: 95 | 96 | ```tsx, ignore 97 | const [results, fields] = await connection.query( 98 | "SELECT * FROM `dinosaurs` WHERE `name` = 'Deno'", 99 | ); 100 | console.log(results); 101 | ``` 102 | 103 | Which gives us a single row result: 104 | 105 | ```tsx, ignore 106 | [{ id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." }]; 107 | ``` 108 | 109 | Finally, we can close the connection: 110 | 111 | ```tsx, ignore 112 | await connection.end(); 113 | ``` 114 | 115 | For more on `mysql2`, check out their documentation 116 | [here](https://github.com/sidorares/node-mysql2). 117 | -------------------------------------------------------------------------------- /node/how_to_with_npm/planetscale.md: -------------------------------------------------------------------------------- 1 | # How to use Planetscale with Deno 2 | 3 | Planetscale is a MySQL-compatible serverless database that is designed with a 4 | developer workflow where developers can create, branch, and deploy databases 5 | from the command line. 6 | 7 | [View source here.](https://github.com/denoland/examples/tree/main/with-planetscale) 8 | 9 | We'll use the Planetscale serverless driver, `@planetscale/database`, to work 10 | with Deno. First we want to create `main.ts` and import the connect method from 11 | this package: 12 | 13 | ```tsx, ignore 14 | import { connect } from "npm:@planetscale/database@^1.4"; 15 | ``` 16 | 17 | ## Configuring our connection 18 | 19 | The connection requires three credentials: host, username, and password. These 20 | are database-specific, so we first need to create a database in Planetscale. You 21 | can do that by following the initial instructions 22 | [here](https://planetscale.com/docs/tutorials/planetscale-quick-start-guide). 23 | Don't worry about adding the schema—we can do that through 24 | `@planetscale/database`. 25 | 26 | Once you have created the database, head to Overview, click "Connect", and 27 | choose "Connect with `@planetscale/database`" to get the host and username. Then 28 | click through to Passwords to create a new password for your database. Once you 29 | have all three you can plug them in directly, or better, store them as 30 | environment variables: 31 | 32 | ```bash 33 | export HOST= 34 | export USERNAME= 35 | export PASSWORD= 36 | ``` 37 | 38 | Then call them using `Deno.env`: 39 | 40 | ```tsx, ignore 41 | const config = { 42 | host: Deno.env.get("HOST"), 43 | username: Deno.env.get("USERNAME"), 44 | password: Deno.env.get("PASSWORD"), 45 | }; 46 | 47 | const conn = connect(config); 48 | ``` 49 | 50 | This will also work on Deno Deploy if you set the environment variables in the 51 | dashboard. Run with: 52 | 53 | ```shell, ignore 54 | deno run --allow-net --allow-env main.ts 55 | ``` 56 | 57 | The `conn` object is now an open connection to our Planetscale database. 58 | 59 | ## Creating and populating our database table 60 | 61 | Now that you have the connection running, you can `conn.execute()` with SQL 62 | commands to create tables and insert the initial data: 63 | 64 | ```tsx, ignore 65 | await conn.execute( 66 | "CREATE TABLE dinosaurs (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255) NOT NULL, description varchar(255) NOT NULL);", 67 | ); 68 | await conn.execute( 69 | "INSERT INTO `dinosaurs` (id, name, description) VALUES (1, 'Aardonyx', 'An early stage in the evolution of sauropods.'), (2, 'Abelisaurus', 'Abels lizard has been reconstructed from a single skull.'), (3, 'Deno', 'The fastest dinosaur that ever lived.')", 70 | ); 71 | ``` 72 | 73 | ## Querying Planetscale 74 | 75 | We can use same `conn.execute()` to also write our queries. Let's get a list of 76 | all our dinosaurs: 77 | 78 | ```tsx, ignore 79 | const results = await conn.execute("SELECT * FROM `dinosaurs`"); 80 | console.log(results.rows); 81 | ``` 82 | 83 | The result: 84 | 85 | ```tsx, ignore 86 | [ 87 | { 88 | id: 1, 89 | name: "Aardonyx", 90 | description: "An early stage in the evolution of sauropods.", 91 | }, 92 | { 93 | id: 2, 94 | name: "Abelisaurus", 95 | description: "Abels lizard has been reconstructed from a single skull.", 96 | }, 97 | { id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." }, 98 | ]; 99 | ``` 100 | 101 | We can also get just a single row from the database by specifying a dinosaur 102 | name: 103 | 104 | ```tsx, ignore 105 | const result = await conn.execute( 106 | "SELECT * FROM `dinosaurs` WHERE `name` = 'Deno'", 107 | ); 108 | console.log(result.rows); 109 | ``` 110 | 111 | Which gives us a single row result: 112 | 113 | ```tsx, ignore 114 | [{ id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." }]; 115 | ``` 116 | 117 | You can find out more about working with Planetscale in their 118 | [docs](https://planetscale.com/docs). 119 | -------------------------------------------------------------------------------- /node/node_specifiers.md: -------------------------------------------------------------------------------- 1 | # `node:` specifiers 2 | 3 | Deno supports using Node.js built-in modules such as 4 | [fs](https://nodejs.org/api/fs.html#file-system), 5 | [path](https://nodejs.org/api/path.html#path), 6 | [process](https://nodejs.org/api/process.html#process), and many more via 7 | `node:` specifiers. 8 | 9 | ```ts, ignore 10 | import { readFileSync } from "node:fs"; 11 | 12 | console.log(readFileSync("deno.json", { encoding: "utf8" })); 13 | ``` 14 | 15 | Take note that importing via a bare specifier (ex. 16 | `import { readFileSync } from "fs";`) is not supported. If you attempt to do so 17 | and the bare specifier matches a Node.js built-in module not found in an import 18 | map, Deno will provide a helpful error message asking if you meant to import 19 | with the `node:` prefix. Additionally the LSP provides a quick fix to update to 20 | a `node:` specifier. 21 | 22 | If you are using code both with Deno and Node.js, the `node:` scheme will work 23 | in both runtimes and it's recommended to update to them for your Node.js code. 24 | -------------------------------------------------------------------------------- /node/npm_specifiers.md: -------------------------------------------------------------------------------- 1 | # `npm:` specifiers 2 | 3 | Since version 1.28, Deno has native support for importing npm packages. This is 4 | done by importing using `npm:` specifiers. 5 | 6 | The way these work is best described with an example that you can run with 7 | `deno run --allow-env`: 8 | 9 | ```ts, ignore 10 | import chalk from "npm:chalk@5"; 11 | 12 | console.log(chalk.green("Hello!")); 13 | ``` 14 | 15 | These npm specifiers have the following format: 16 | 17 | ```ts, ignore 18 | npm:[@][/] 19 | ``` 20 | 21 | Another example with express: 22 | 23 | ```js, ignore 24 | // main.js 25 | import express from "npm:express@^4.17"; 26 | const app = express(); 27 | 28 | app.get("/", (req, res) => { 29 | res.send("Hello World"); 30 | }); 31 | 32 | app.listen(3000); 33 | console.log("listening on http://localhost:3000/"); 34 | ``` 35 | 36 | Then doing the following will start a simple express server: 37 | 38 | ```sh 39 | $ deno run -A main.js 40 | listening on http://localhost:3000/ 41 | ``` 42 | 43 | When doing this, no `npm install` is necessary and no `node_modules` folder is 44 | created. These packages are also subject to the same permissions as Deno 45 | applications. 46 | 47 | ## npm executable scripts 48 | 49 | npm packages with `bin` entries can be executed from the command line without an 50 | `npm install` using a specifier in the following format: 51 | 52 | ```ts, ignore 53 | npm:[@][/] 54 | ``` 55 | 56 | For example: 57 | 58 | ```sh 59 | $ deno run --allow-env --allow-read npm:cowsay@1.5.0 Hello there! 60 | ______________ 61 | < Hello there! > 62 | -------------- 63 | \ ^__^ 64 | \ (oo)\_______ 65 | (__)\ )\/\ 66 | ||----w | 67 | || || 68 | 69 | $ deno run --allow-env --allow-read npm:cowsay@1.5.0/cowthink What to eat? 70 | ______________ 71 | ( What to eat? ) 72 | -------------- 73 | o ^__^ 74 | o (oo)\_______ 75 | (__)\ )\/\ 76 | ||----w | 77 | || || 78 | ``` 79 | 80 | ## TypeScript types 81 | 82 | Many packages ship with types out of the box, you can import those and use them 83 | with types easily: 84 | 85 | ```ts, ignore 86 | import chalk from "npm:chalk@5"; 87 | ``` 88 | 89 | Some packages do not though, but you can specify their types with a 90 | [`@deno-types`](../advanced/typescript/types.md) directive. For example, using a 91 | [`@types`](https://www.typescriptlang.org/docs/handbook/2/type-declarations.html#definitelytyped--types) 92 | package: 93 | 94 | ```ts, ignore 95 | // @deno-types="npm:@types/express@^4.17" 96 | import express from "npm:express@^4.17"; 97 | ``` 98 | 99 | ### Including Node types 100 | 101 | Node ships with many built-in types like `Buffer` that might be referenced in an 102 | npm package's types. To load these you must add a types reference directive to 103 | the `@types/node` package: 104 | 105 | ```ts, ignore 106 | /// 107 | ``` 108 | 109 | Note that it is fine to not specify a version for this in most cases because 110 | Deno will try to keep it in sync with its internal Node code, but you can always 111 | override the version used if necessary. 112 | 113 | ## `--node-modules-dir` flag 114 | 115 | npm specifiers resolve npm packages to a central global npm cache. This works 116 | well in most cases and is ideal since it uses less space and doesn't require a 117 | node_modules directory. That said, you may find cases where an npm package 118 | expects itself to be executing from a `node_modules` directory. To improve 119 | compatibility and support those packages, you can use the `--node-modules-dir` 120 | flag. 121 | 122 | For example, given `main.ts`: 123 | 124 | ```ts 125 | import chalk from "npm:chalk@5"; 126 | 127 | console.log(chalk.green("Hello")); 128 | ``` 129 | 130 | Running this script with a `--node-modules-dir` like so... 131 | 132 | ```sh 133 | deno run --node-modules-dir main.ts 134 | ``` 135 | 136 | ...will create a `node_modules` folder in the current directory with a similar 137 | folder structure to npm. 138 | 139 | ![](../images/node_modules_dir.png) 140 | 141 | Note that this is all done automatically when calling deno run and there is no 142 | separate install command necessary. 143 | 144 | Alternatively, if you wish to disable the creation of a `node_modules` directory 145 | entirely, you can set this flag to false (ex. `--node-modules-dir=false`) or add 146 | a `"nodeModulesDir": false` entry to your deno.json configuration file to make 147 | the setting apply to the entire directory tree. 148 | 149 | In the case where you want to modify the contents of the `node_modules` 150 | directory before execution, you can run `deno cache` with `--node-modules-dir`, 151 | modify the contents, then run the script. 152 | 153 | For example: 154 | 155 | ```sh 156 | deno cache --node-modules-dir main.ts 157 | deno run --allow-read=. --allow-write=. scripts/your_script_to_modify_node_modules_dir.ts 158 | deno run --node-modules-dir main.ts 159 | ``` 160 | -------------------------------------------------------------------------------- /node/package_json.md: -------------------------------------------------------------------------------- 1 | # package.json compatibility 2 | 3 | Deno supports resolving dependencies based on a `package.json` file in the 4 | current or ancestor directories. This is similar to how Node.js resolves 5 | dependencies. We recommend using import maps with `deno.json` which is explained 6 | [here](../basics/import_maps.md). 7 | 8 | **package.json** 9 | 10 | ```json 11 | { 12 | "name": "@deno/my-example-project", 13 | "description": "An example app created with Deno", 14 | "type": "module", 15 | "scripts": { 16 | "dev": "deno run --allow-env --allow-sys main.ts" 17 | }, 18 | "dependencies": { 19 | "chalk": "^5.2" 20 | } 21 | } 22 | ``` 23 | 24 | **main.ts** 25 | 26 | ```ts, ignore 27 | import chalk from "chalk"; 28 | 29 | console.log(chalk.green("Hello from Deno!")); 30 | ``` 31 | 32 | Then we can run this script: 33 | 34 | ```shell, ignore 35 | > deno run --allow-env --allow-sys main.ts 36 | Hello from Deno! 37 | ``` 38 | 39 | Or also execute package.json scripts via `deno task`: 40 | 41 | ```shell, ignore 42 | > deno task dev 43 | Hello from Deno! 44 | ``` 45 | -------------------------------------------------------------------------------- /references.md: -------------------------------------------------------------------------------- 1 | # References 2 | 3 | This chapter contains links to reference manuals and sheets, including: 4 | 5 | - [Deno Standard APIs](https://deno.land/api@$CLI_VERSION) 6 | - [Standard Library](https://deno.land/std@$STD_VERSION?doc) 7 | - [Deno-native third party modules](https://deno.land/x) 8 | - [Full Guide to Using Visual Studio Code](./references/vscode_deno.md) 9 | - [Node to Deno Cheatsheet](./references/cheatsheet.md) 10 | - [Contributing to Deno](./references/contributing.md) 11 | -------------------------------------------------------------------------------- /references/cheatsheet.md: -------------------------------------------------------------------------------- 1 | # Node.js -> Deno cheatsheet 2 | 3 | | Node.js | Deno | 4 | | -------------------------------------- | ---------------------------------------------- | 5 | | `node file.js` | `deno run file.js` | 6 | | `ts-node file.ts` | `deno run file.ts` | 7 | | `node -e` | `deno eval` | 8 | | `npm i -g` | `deno install` | 9 | | `npm i` / `npm install` | _n/a_ ¹ | 10 | | `npm run` | `deno task` | 11 | | `eslint` | `deno lint` | 12 | | `prettier` | `deno fmt` | 13 | | `package.json` | `deno.json` / `deno.jsonc` / `import_map.json` | 14 | | `tsc` | `deno check` ² | 15 | | `typedoc` | `deno doc` | 16 | | `jest` / `ava` / `mocha` / `tap` / etc | `deno test` | 17 | | `nodemon` | `deno run/lint/test --watch` | 18 | | `nexe` / `pkg` | `deno compile` | 19 | | `npm explain` | `deno info` | 20 | | `nvm` / `n` / `fnm` | `deno upgrade` | 21 | | `tsserver` | `deno lsp` | 22 | | `nyc` / `c8` / `istanbul` | `deno coverage` | 23 | | benchmarks | `deno bench` | 24 | 25 | ¹ See [Modules](../basics/modules.md), the runtime downloads and caches the code 26 | on first use. 27 | 28 | ² Type checking happens automatically, TypeScript compiler is built into the 29 | `deno` binary. 30 | -------------------------------------------------------------------------------- /references/contributing/architecture.md: -------------------------------------------------------------------------------- 1 | # Internal Details 2 | 3 | ## Deno and Linux analogy 4 | 5 | | **Linux** | **Deno** | 6 | | ------------------------------: | :------------------------------- | 7 | | Processes | Web Workers | 8 | | Syscalls | Ops | 9 | | File descriptors (fd) | [Resource ids (rid)](#resources) | 10 | | Scheduler | Tokio | 11 | | Userland: libc++ / glib / boost | https://deno.land/std/ | 12 | | /proc/\$\$/stat | [Deno.metrics()](#metrics) | 13 | | man pages | deno types | 14 | 15 | ### Resources 16 | 17 | Resources (AKA `rid`) are Deno's version of file descriptors. They are integer 18 | values used to refer to open files, sockets, and other concepts. For testing it 19 | would be good to be able to query the system for how many open resources there 20 | are. 21 | 22 | ```ts 23 | console.log(Deno.resources()); 24 | // { 0: "stdin", 1: "stdout", 2: "stderr" } 25 | Deno.close(0); 26 | console.log(Deno.resources()); 27 | // { 1: "stdout", 2: "stderr" } 28 | ``` 29 | 30 | ### Metrics 31 | 32 | Metrics is Deno's internal counter for various statistics. 33 | 34 | ```shell 35 | > console.table(Deno.metrics()) 36 | ┌─────────────────────────┬───────────┐ 37 | │ (idx) │ Values │ 38 | ├─────────────────────────┼───────────┤ 39 | │ opsDispatched │ 9 │ 40 | │ opsDispatchedSync │ 0 │ 41 | │ opsDispatchedAsync │ 0 │ 42 | │ opsDispatchedAsyncUnref │ 0 │ 43 | │ opsCompleted │ 9 │ 44 | │ opsCompletedSync │ 0 │ 45 | │ opsCompletedAsync │ 0 │ 46 | │ opsCompletedAsyncUnref │ 0 │ 47 | │ bytesSentControl │ 504 │ 48 | │ bytesSentData │ 0 │ 49 | │ bytesReceived │ 856 │ 50 | └─────────────────────────┴───────────┘ 51 | ``` 52 | 53 | ## Schematic diagram 54 | 55 | ![architectural schematic](https://deno.land/images/schematic_v0.2.png) 56 | 57 | ## Conference 58 | 59 | - Ryan Dahl. (May 27, 2020). 60 | [An interesting case with Deno](https://www.youtube.com/watch?v=1b7FoBwxc7E). 61 | Deno Israel. 62 | - Bartek Iwańczuk. (Oct 6, 2020). 63 | [Deno internals - how modern JS/TS runtime is 64 | built](https://www.youtube.com/watch?v=AOvg_GbnsbA&t=35m13s). Paris Deno. 65 | -------------------------------------------------------------------------------- /references/contributing/release_schedule.md: -------------------------------------------------------------------------------- 1 | # Release Schedule 2 | 3 | A new minor release for the `deno` cli is released every month, on the third 4 | Thursday of the month. 5 | 6 | See [Milestones on Deno's GitHub](https://github.com/denoland/deno/milestones) 7 | for the upcoming releases. 8 | 9 | There are usually two or three patch releases (done weekly) after a minor 10 | releases; after that a merge window for new features opens for the upcoming 11 | minor release. 12 | 13 | Stable releases can be found on the 14 | [GitHub releases page](https://github.com/denoland/deno/releases). 15 | 16 | ## Canary channel 17 | 18 | In addition to the stable channel described above, canaries are released 19 | multiple times daily (for each commit on main). You can upgrade to the latest 20 | canary release by running: 21 | 22 | ``` 23 | deno upgrade --canary 24 | ``` 25 | 26 | To update to a specific canary, pass the commit hash in the `--version` option: 27 | 28 | ``` 29 | deno upgrade --canary --version=973af61d8bb03c1709f61e456581d58386ed4952 30 | ``` 31 | 32 | To switch back to the stable channel, run `deno upgrade`. 33 | 34 | Canaries can be downloaded from https://dl.deno.land. 35 | -------------------------------------------------------------------------------- /references/contributing/web_platform_tests.md: -------------------------------------------------------------------------------- 1 | # Web Platform Test 2 | 3 | Deno uses a custom test runner for Web Platform Tests. It can be found at 4 | `./tools/wpt.ts`. 5 | 6 | ## Running tests 7 | 8 | > If you are on Windows, or your system does not support hashbangs, prefix all 9 | > `./tools/wpt.ts` commands with 10 | > `deno run --unstable --allow-write --allow-read --allow-net --allow-env --allow-run`. 11 | 12 | Before attempting to run WPT tests for the first time, please run the WPT setup. 13 | You must also run this command every time the `./test_util/wpt` submodule is 14 | updated: 15 | 16 | ```shell 17 | ./tools/wpt.ts setup 18 | ``` 19 | 20 | To run all available web platform tests, run the following command: 21 | 22 | ```shell 23 | ./tools/wpt.ts run 24 | 25 | # You can also filter which test files to run by specifying filters: 26 | ./tools/wpt.ts run -- streams/piping/general hr-time 27 | ``` 28 | 29 | The test runner will run each web platform test and record its status (failed or 30 | ok). It will then compare this output to the expected output of each test as 31 | specified in the `./tools/wpt/expectation.json` file. This file is a nested JSON 32 | structure that mirrors the `./test_utils/wpt` directory. It describes for each 33 | test file, if it should pass as a whole (all tests pass, `true`), if it should 34 | fail as a whole (test runner encounters an exception outside of a test or all 35 | tests fail, `false`), or which tests it expects to fail (a string array of test 36 | case names). 37 | 38 | ## Updating enabled tests or expectations 39 | 40 | You can update the `./tools/wpt/expectation.json` file manually by changing the 41 | value of each of the test file entries in the JSON structure. The alternative 42 | and preferred option is to have the WPT runner run all, or a filtered subset of 43 | tests, and then automatically update the `expectation.json` file to match the 44 | current reality. You can do this with the `./wpt.ts update` command. Example: 45 | 46 | ```shell 47 | ./tools/wpt.ts update -- hr-time 48 | ``` 49 | 50 | After running this command the `expectation.json` file will match the current 51 | output of all the tests that were run. This means that running `wpt.ts run` 52 | right after a `wpt.ts update` should always pass. 53 | 54 | ## Subcommands 55 | 56 | ### `setup` 57 | 58 | Validate that your environment is configured correctly, or help you configure 59 | it. 60 | 61 | This will check that the python3 (or `python.exe` on Windows) is actually 62 | Python 3. 63 | 64 | You can specify the following flags to customize behaviour: 65 | 66 | ``` 67 | --rebuild 68 | Rebuild the manifest instead of downloading. This can take up to 3 minutes. 69 | 70 | --auto-config 71 | Automatically configure /etc/hosts if it is not configured (no prompt will be shown). 72 | ``` 73 | 74 | ### `run` 75 | 76 | Run all tests like specified in `expectation.json`. 77 | 78 | You can specify the following flags to customize behaviour: 79 | 80 | ``` 81 | --release 82 | Use the ./target/release/deno binary instead of ./target/debug/deno 83 | 84 | --quiet 85 | Disable printing of `ok` test cases. 86 | 87 | --json= 88 | Output the test results as JSON to the file specified. 89 | ``` 90 | 91 | You can also specify exactly which tests to run by specifying one of more 92 | filters after a `--`: 93 | 94 | ``` 95 | ./tools/wpt.ts run -- hr-time streams/piping/general 96 | ``` 97 | 98 | ### `update` 99 | 100 | Update the `expectation.json` to match the current reality. 101 | 102 | You can specify the following flags to customize behaviour: 103 | 104 | ``` 105 | --release 106 | Use the ./target/release/deno binary instead of ./target/debug/deno 107 | 108 | --quiet 109 | Disable printing of `ok` test cases. 110 | 111 | --json= 112 | Output the test results as JSON to the file specified. 113 | ``` 114 | 115 | You can also specify exactly which tests to run by specifying one of more 116 | filters after a `--`: 117 | 118 | ``` 119 | ./tools/wpt.ts update -- hr-time streams/piping/general 120 | ``` 121 | 122 | ## FAQ 123 | 124 | ### Upgrading the wpt submodule: 125 | 126 | ```shell 127 | cd test_util/wpt/ 128 | git fetch origin 129 | git checkout origin/epochs/daily 130 | cd ../../ 131 | git add ./test_util/wpt 132 | ``` 133 | 134 | All contributors will need to rerun `./tools/wpt.ts setup` after this. 135 | 136 | Since upgrading WPT usually requires updating the expectations to cover all 137 | sorts of upstream changes, it's best to do that as a separate PR, rather than as 138 | part of a PR that implements a fix or feature. 139 | -------------------------------------------------------------------------------- /references/vscode_deno/testing_api.md: -------------------------------------------------------------------------------- 1 | # Testing API 2 | 3 | The `vscode_deno` extension implements a client for the vscode 4 | [Testing API](https://code.visualstudio.com/api/extension-guides/testing) and 5 | when using a version of Deno that supports the testing API, tests in your 6 | project will be displayed within your IDE for Deno enabled projects. 7 | 8 | ## Test display 9 | 10 | When both the editor and the version of Deno support the testing API, the _Test 11 | Explorer_ view will activate represented by a beaker icon, which will provide 12 | you with a side panel of tests that have been discovered in your project. 13 | 14 | Also, next to tests identified in the code, there will be decorations which 15 | allow you to run and see the status of each test, as well as there will be 16 | entries in the command palette for tests. 17 | 18 | ## Discovering tests 19 | 20 | Currently, Deno will only discover tests that are part of the "known" modules 21 | inside a workspace. A module becomes "known" when it is opened in the editor, or 22 | another module which imports that module is "known" inside the editor. 23 | 24 | In the future, tests will be discovered in a similar fashion to the way the 25 | `deno test` subcommand discovers tests as part of the root of the workspace. 26 | 27 | ## Running tests 28 | 29 | You can run tests from the Test Explorer view, from the decorations next to the 30 | tests when viewing the test code, or via the command palette. You can also use 31 | the filter function in the Text Explorer view to exclude certain tests from a 32 | test run. 33 | 34 | Currently, Deno only supports the "run" test capability. We will be adding a 35 | debug run mode as well as a coverage run mode in the future. We will also be 36 | integrating the benchmarking tests as a _tag_, so they can be run (or excluded) 37 | from your test runs. 38 | 39 | The Deno language server does not spin up a new CLI subprocess. It instead 40 | spawns a new thread and JavaScript runtime per test module to execute the tests. 41 | 42 | ## Test output 43 | 44 | Any `console.log()` that occurs in your tests will be sent to the test output 45 | window within vscode. 46 | 47 | When a test fails, the failure message, including the stack trace, will be 48 | available when inspecting the test results in vscode. 49 | 50 | ## How tests are structured 51 | 52 | Test will be displayed in the Test Explorer at the top level with the module 53 | that contains the test. Inside the module will be all the tests that have been 54 | discovered, and if you are using test steps, they will be included under the 55 | test. 56 | 57 | In most cases, the Deno language server will be able to statically identify 58 | tests, but if you are generating tests dynamically, Deno may not be aware of 59 | them until runtime. In these cases it may not be possible to filter these tests 60 | out of a run, but they will be added to the explorer view as they are 61 | encountered. 62 | 63 | ## Configuration 64 | 65 | By default, tests are executed in a similar fashion to if you were to use 66 | `deno test --allow-all` on the command line. These default arguments can be 67 | changed by setting the _Deno > Testing: Args_ option in your user or workspace 68 | settings (or `deno.testing.args` if you are configuring manually). Add 69 | individual arguments here which you would have used with the `deno test` 70 | subcommand. 71 | 72 | Based on other settings that you have, those options will be automatically 73 | merged into the "command line" used when running tests unless explicitly 74 | provided in the _Deno > Testing: Args_ setting. For example if you have a _Deno: 75 | Import Map_ (`deno.importMap`) set, the value of that will be used unless you 76 | have provided an explicit `--import-map` value in the testing args setting. 77 | 78 | ## Known limitations and caveats 79 | 80 | Because of the way the Deno test runner runs, it is not possible to exclude (or 81 | explicitly include) a test step. While the vscode UI will allow you to do this, 82 | by for example, choosing to run a specific test step, all test steps in that 83 | test will be run (but vscode will not update the results for them). So if there 84 | are other side effects in the test case, they may occur. 85 | -------------------------------------------------------------------------------- /runtime.md: -------------------------------------------------------------------------------- 1 | # Runtime 2 | 3 | Documentation for all runtime functions (Web APIs + `Deno` global) can be found 4 | at [`/api`](/api) or with adding the _unstable_ APIs which are enabled via the 5 | `--unstable` flag at [`/api?unstable`](/api?unstable). 6 | 7 | ## Web Platform APIs 8 | 9 | For APIs where a web standard already exists, like `fetch` for HTTP requests, 10 | Deno uses these rather than inventing a new proprietary API. 11 | 12 | For more details, view the chapter on 13 | [Web Platform APIs](./runtime/web_platform_apis.md). 14 | 15 | ## `Deno` global 16 | 17 | All APIs that are not web standard are contained in the global `Deno` namespace. 18 | It has the APIs for reading from files, opening TCP sockets, 19 | [serving HTTP](./runtime/http_server_apis.md), and executing subprocesses, etc. 20 | 21 | For more details, view the chapter on 22 | [Built-in APIs](./runtime/builtin_apis.md). 23 | 24 | The TypeScript definitions for the Deno namespaces can be found in the 25 | [`lib.deno.ns.d.ts`](https://github.com/denoland/deno/blob/$CLI_VERSION/cli/tsc/dts/lib.deno.ns.d.ts) 26 | file. 27 | -------------------------------------------------------------------------------- /runtime/builtin_apis.md: -------------------------------------------------------------------------------- 1 | # Built-in API 2 | 3 | The global Deno namespace contains APIs that are not web standard, including 4 | APIs for reading from files, opening TCP sockets, serving HTTP, and executing 5 | subprocesses, etc. 6 | 7 | For a full list of Deno Built-in APIs, see the 8 | [reference](https://deno.land/api@$CLI_VERSION?s=Deno). Below we highlight some 9 | of the most important. 10 | 11 | ## Errors 12 | 13 | The Deno runtime comes with 14 | [20 error classes](https://deno.land/api@$CLI_VERSION#Errors) that can be raised 15 | in response to a number of conditions. 16 | 17 | Some examples are: 18 | 19 | ```sh 20 | Deno.errors.NotFound; 21 | Deno.errors.WriteZero; 22 | ``` 23 | 24 | They can be used as below: 25 | 26 | ```ts 27 | try { 28 | const file = await Deno.open("./some/file.txt"); 29 | } catch (error) { 30 | if (error instanceof Deno.errors.NotFound) { 31 | console.error("the file was not found"); 32 | } else { 33 | // otherwise re-throw 34 | throw error; 35 | } 36 | } 37 | ``` 38 | 39 | ## File System 40 | 41 | The Deno runtime comes with 42 | [various functions for working with files and directories](https://deno.land/api@$CLI_VERSION#File_System). 43 | You will need to use --allow-read and --allow-write permissions to gain access 44 | to the file system. 45 | 46 | Refer to the links below for code examples of how to use the file system 47 | functions. 48 | 49 | - [Reading files in several different ways](https://examples.deno.land/reading-files) 50 | - [Reading files in streams](../examples/file_server.md) 51 | - [Reading a text file (`Deno.readTextFile`)](../examples/read_write_files.md#reading-a-text-file) 52 | - [Writing a text file (`Deno.writeTextFile`)](../examples/read_write_files.md#writing-a-text-file) 53 | 54 | ## I/O 55 | 56 | The Deno runtime comes with 57 | [built-in functions for working with resources and I/O](https://deno.land/api@$CLI_VERSION#I/O). 58 | 59 | Refer to the links below for code examples for common functions. 60 | 61 | - [Closing resources (`Deno.close`)](https://doc.deno.land/deno/stable/~/Deno.close) 62 | - [Seeking a certain position within the resource (`Deno.seek`)](https://doc.deno.land/deno/stable/~/Deno.seek) 63 | 64 | ## Network 65 | 66 | The Deno runtime comes with 67 | [built-in functions for dealing with connections to network ports](https://deno.land/api@$CLI_VERSION#Network). 68 | 69 | Refer to the links below for code examples for common functions. 70 | 71 | - [Connect to the hostname and port (`Deno.connect`)](https://doc.deno.land/deno/stable/~/Deno.connect) 72 | - [Announcing on the local transport address (`Deno.listen`)](https://doc.deno.land/deno/stable/~/Deno.listen) 73 | 74 | ## Sub Process 75 | 76 | The Deno runtime comes with 77 | [built-in functions for spinning up subprocesses](https://deno.land/api@$CLI_VERSION#Sub_Process). 78 | 79 | Refer to the links below for code samples of how to create a subprocess. 80 | 81 | - [Creating a subprocess (`Deno.Command`)](../examples/subprocess.md) 82 | -------------------------------------------------------------------------------- /runtime/import_meta_api.md: -------------------------------------------------------------------------------- 1 | # `import.meta` API 2 | 3 | Deno supports a number of methods on the 4 | [`import.meta`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta) 5 | API: 6 | 7 | - `import.meta.url`: returns the URL of the current module. 8 | - `import.meta.main`: returns whether the current module is the entry point to 9 | your program. 10 | - `import.meta.resolve`: resolve specifiers relative to the current module. 11 | 12 | ## `import.meta.resolve` Example 13 | 14 | ```ts 15 | const worker = new Worker(import.meta.resolve("./worker.ts")); 16 | ``` 17 | 18 | The `import.meta.resolve` API takes into account the currently applied import 19 | map, which gives you the ability to resolve "bare" specifiers as well. 20 | 21 | With such import map loaded... 22 | 23 | ```json 24 | { 25 | "imports": { 26 | "fresh": "https://deno.land/x/fresh@1.0.1/dev.ts" 27 | } 28 | } 29 | ``` 30 | 31 | ...you can now resolve: 32 | 33 | ```js 34 | // resolve.js 35 | console.log(import.meta.resolve("fresh")); 36 | ``` 37 | 38 | ```sh 39 | $ deno run resolve.js 40 | https://deno.land/x/fresh@1.0.1/dev.ts 41 | ``` 42 | -------------------------------------------------------------------------------- /runtime/kv/key_expiration.md: -------------------------------------------------------------------------------- 1 | # Key Expiration 2 | 3 | > ⚠️ Deno KV is currently **experimental** and **subject to change**. While we do 4 | > our best to ensure data durability, data loss is possible, especially around 5 | > Deno updates. We recommend that you backup your data regularly and consider 6 | > storing data in a secondary store for the time being. 7 | 8 | > 🌐 Deno KV is available for Deno Deploy. 9 | > [Read the Deno Deploy KV docs](https://deno.com/deploy/docs/kv). 10 | 11 | Since version 1.36.2, Deno KV supports key expiration. This allows an expiration 12 | timestamp to be associated with a key, after which the key will be automatically 13 | deleted from the database: 14 | 15 | ```ts,ignore 16 | const kv = await Deno.openKv(); 17 | 18 | // `expireIn` is the number of milliseconds after which the key will expire. 19 | function addSession(session: Session, expireIn: number) { 20 | await kv.set(["sessions", session.id], session, { expireIn }); 21 | } 22 | ``` 23 | 24 | Key expiration is supported on both Deno CLI and Deno Deploy. 25 | 26 | ## Atomic expiration of multiple keys 27 | 28 | If multiple keys are set in the same atomic operation and have the same 29 | `expireIn` value, the expiration of those keys will be atomic. For example: 30 | 31 | ```ts,ignore 32 | const kv = await Deno.openKv(); 33 | 34 | function addUnverifiedUser( 35 | user: User, 36 | verificationToken: string, 37 | expireIn: number, 38 | ) { 39 | await kv.atomic() 40 | .set(["users", user.id], user, { expireIn }) 41 | .set(["verificationTokens", verificationToken], user.id, { expireIn }) 42 | .commit(); 43 | } 44 | ``` 45 | 46 | ## Caveats 47 | 48 | The expire timestamp specifies the _earliest_ time after which the key can be 49 | deleted from the database. An implementation is allowed to expire a key at any 50 | time after the specified timestamp, but not before. If you need to strictly 51 | enforce an expiration time (e.g. for security purposes), please also add it as a 52 | field of your value and do a check after retrieving the value from the database. 53 | -------------------------------------------------------------------------------- /runtime/location_api.md: -------------------------------------------------------------------------------- 1 | # Location API 2 | 3 | Deno supports the 4 | [`location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) 5 | global from the web. Please read on. 6 | 7 | ## Location flag 8 | 9 | There is no "web page" whose URL we can use for a location in a Deno process. We 10 | instead allow users to emulate a document location by specifying one on the CLI 11 | using the `--location` flag. It can be a `http` or `https` URL. 12 | 13 | ```ts 14 | // deno run --location https://example.com/path main.ts 15 | 16 | console.log(location.href); 17 | // "https://example.com/path" 18 | ``` 19 | 20 | You must pass `--location ` for this to work. If you don't, any access to 21 | the `location` global will throw an error. 22 | 23 | ```ts 24 | // deno run main.ts 25 | 26 | console.log(location.href); 27 | // error: Uncaught ReferenceError: Access to "location", run again with --location . 28 | ``` 29 | 30 | Setting `location` or any of its fields will normally cause navigation in 31 | browsers. This is not applicable in Deno, so it will throw in this situation. 32 | 33 | ```ts 34 | // deno run --location https://example.com/path main.ts 35 | 36 | location.pathname = "./foo"; 37 | // error: Uncaught NotSupportedError: Cannot set "location.pathname". 38 | ``` 39 | 40 | ## Extended usage 41 | 42 | On the web, resource resolution (excluding modules) typically uses the value of 43 | `location.href` as the root on which to base any relative URLs. This affects 44 | some web APIs adopted by Deno. 45 | 46 | ### Fetch API 47 | 48 | ```ts 49 | // deno run --location https://api.github.com/ --allow-net main.ts 50 | 51 | const response = await fetch("./orgs/denoland"); 52 | // Fetches "https://api.github.com/orgs/denoland". 53 | ``` 54 | 55 | The `fetch()` call above would throw if the `--location` flag was not passed, 56 | since there is no web-analogous location to base it onto. 57 | 58 | ### Worker modules 59 | 60 | ```ts 61 | // deno run --location https://example.com/index.html --allow-net main.ts 62 | 63 | const worker = new Worker("./workers/hello.ts", { type: "module" }); 64 | // Fetches worker module at "https://example.com/workers/hello.ts". 65 | ``` 66 | 67 | ## Only use if necessary 68 | 69 | For the above use cases, it is preferable to pass URLs in full rather than 70 | relying on `--location`. You can manually base a relative URL using the `URL` 71 | constructor if needed. 72 | 73 | The `--location` flag is intended for those who have some specific purpose in 74 | mind for emulating a document location and are aware that this will only work at 75 | application-level. However, you may also use it to silence errors from a 76 | dependency which is frivolously accessing the `location` global. 77 | -------------------------------------------------------------------------------- /runtime/stability.md: -------------------------------------------------------------------------------- 1 | # Stability 2 | 3 | As of Deno 1.0.0, the `Deno` namespace APIs are stable. That means we will 4 | strive to make code working under 1.0.0 continue to work in future versions. 5 | 6 | However, not all of Deno's features are ready for production yet. Features which 7 | are not ready, because they are still in draft phase, are locked behind the 8 | `--unstable` command line flag. 9 | 10 | ```shell 11 | deno run --unstable mod_which_uses_unstable_stuff.ts 12 | ``` 13 | 14 | Passing this flag does a few things: 15 | 16 | - It enables the use of unstable APIs during runtime. 17 | - It adds the 18 | [`lib.deno.unstable.d.ts`](https://doc.deno.land/https://raw.githubusercontent.com/denoland/deno/main/cli/tsc/dts/lib.deno.unstable.d.ts) 19 | file to the list of TypeScript definitions that are used for type checking. 20 | This includes the output of `deno types`. 21 | 22 | You should be aware that many unstable APIs have **not undergone a security 23 | review**, are likely to have **breaking API changes** in the future, and are 24 | **not ready for production**. 25 | 26 | ## Standard modules 27 | 28 | Deno's standard modules (https://deno.land/std@STD_VERSION) are not yet stable. 29 | We currently version the standard modules differently from the CLI to reflect 30 | this. Note that unlike the `Deno` namespace, the use of the standard modules do 31 | not require the `--unstable` flag (unless the standard module itself makes use 32 | of an unstable Deno feature). 33 | -------------------------------------------------------------------------------- /runtime/web_storage_api.md: -------------------------------------------------------------------------------- 1 | # Web Storage API 2 | 3 | Deno 1.10 introduced the 4 | [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) 5 | which provides an API for storing string keys and values. Persisting data works 6 | similar to a browser, and has a 10MB storage limit. The global `sessionStorage` 7 | object only persists data for the current execution context, while 8 | `localStorage` persists data from execution to execution. 9 | 10 | In a browser, `localStorage` persists data uniquely per origin (effectively the 11 | protocol plus hostname plus port). As of Deno 1.16, Deno has a set of rules to 12 | determine what is a unique storage location: 13 | 14 | - When using the `--location` flag, the origin for the location is used to 15 | uniquely store the data. That means a location of `http://example.com/a.ts` 16 | and `http://example.com/b.ts` and `http://example.com:80/` would all share the 17 | same storage, but `https://example.com/` would be different. 18 | - If there is no location specifier, but there is a `--config` configuration 19 | file specified, the absolute path to that configuration file is used. That 20 | means `deno run --config deno.jsonc a.ts` and 21 | `deno run --config deno.jsonc b.ts` would share the same storage, but 22 | `deno run --config tsconfig.json a.ts` would be different. 23 | - If there is no configuration or location specifier, Deno uses the absolute 24 | path to the main module to determine what storage is shared. The Deno REPL 25 | generates a "synthetic" main module that is based off the current working 26 | directory where `deno` is started from. This means that multiple invocations 27 | of the REPL from the same path will share the persisted `localStorage` data. 28 | 29 | This means, unlike versions prior to 1.16, `localStorage` is always available in 30 | the main process. 31 | 32 | ## Example 33 | 34 | The following snippet accesses the local storage bucket for the current origin 35 | and adds a data item to it using `setItem()`. 36 | 37 | ```ts 38 | localStorage.setItem("myDemo", "Deno App"); 39 | ``` 40 | 41 | The syntax for reading the localStorage item is as follows: 42 | 43 | ```ts 44 | const cat = localStorage.getItem("myDemo"); 45 | ``` 46 | 47 | The syntax for removing the localStorage item is as follows: 48 | 49 | ```ts 50 | localStorage.removeItem("myDemo"); 51 | ``` 52 | 53 | The syntax for removing all the localStorage items is as follows: 54 | 55 | ```ts 56 | localStorage.clear(); 57 | ``` 58 | -------------------------------------------------------------------------------- /runtime/webassembly.md: -------------------------------------------------------------------------------- 1 | # Using WebAssembly 2 | 3 | Designed to be used alongside JavaScript to speed up key application components, 4 | [WebAssembly](https://webassembly.org/) can have much higher, and more 5 | consistent execution speed than JavaScript, similar to C, C++, or Rust. Deno can 6 | execute WebAssembly modules with the same interfaces that 7 | [browsers provide](https://developer.mozilla.org/en-US/docs/WebAssembly). 8 | 9 | In this chapter we will discuss: 10 | 11 | 1. [Using WebAssembly in Deno](webassembly/using_wasm.md) 12 | 2. [Using the Streaming WebAssembly APIs](webassembly/using_streaming_wasm.md) 13 | 3. [Helpful Resources](webassembly/wasm_resources.md) 14 | -------------------------------------------------------------------------------- /runtime/webassembly/using_streaming_wasm.md: -------------------------------------------------------------------------------- 1 | # Using the Streaming WebAssembly APIs 2 | 3 | The 4 | [most efficient](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming) 5 | way to fetch, compile and instantiate a WebAssembly module is to use the 6 | streaming variants of the WebAssembly API. For example, you can use 7 | `instantiateStreaming` combined with `fetch` to perform all three steps in one 8 | go: 9 | 10 | ```ts 11 | const { instance, module } = await WebAssembly.instantiateStreaming( 12 | fetch("https://wpt.live/wasm/incrementer.wasm"), 13 | ); 14 | 15 | const increment = instance.exports.increment as (input: number) => number; 16 | console.log(increment(41)); 17 | ``` 18 | 19 | Note that the `.wasm` file must be served with the `application/wasm` MIME type. 20 | If you want to do additional work on the module before instantiation you can 21 | instead use `compileStreaming`: 22 | 23 | ```ts 24 | const module = await WebAssembly.compileStreaming( 25 | fetch("https://wpt.live/wasm/incrementer.wasm"), 26 | ); 27 | 28 | /* do some more stuff */ 29 | 30 | const instance = await WebAssembly.instantiate(module); 31 | instance.exports.increment as (input: number) => number; 32 | ``` 33 | 34 | If for some reason you cannot make use of the streaming methods you can fall 35 | back to the less efficient `compile` and `instantiate` methods. See for example 36 | the 37 | [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate). 38 | For a more in-depth look on what makes the streaming methods more performant, 39 | see for example 40 | [this post](https://hacks.mozilla.org/2018/01/making-webassembly-even-faster-firefoxs-new-streaming-and-tiering-compiler/). 41 | -------------------------------------------------------------------------------- /runtime/webassembly/using_wasm.md: -------------------------------------------------------------------------------- 1 | # Using WebAssembly in Deno 2 | 3 | To run WebAssembly in Deno, all you need is a binary to run. WebAssembly is a 4 | binary data format. This means that `.wasm` files are not directly human 5 | readable, and not intended to be written by hand. Instead a compiler for a 6 | language like Rust, C++, or Go _emits_ `.wasm` files. 7 | 8 | The following binary exports a `main` function that just returns `42` upon 9 | invocation: 10 | 11 | 12 | ```ts 13 | const wasmCode = new Uint8Array([ 14 | 0, 97, 115, 109, 1, 0, 0, 0, 1, 133, 128, 128, 128, 0, 1, 96, 0, 1, 127, 15 | 3, 130, 128, 128, 128, 0, 1, 0, 4, 132, 128, 128, 128, 0, 1, 112, 0, 0, 16 | 5, 131, 128, 128, 128, 0, 1, 0, 1, 6, 129, 128, 128, 128, 0, 0, 7, 145, 17 | 128, 128, 128, 0, 2, 6, 109, 101, 109, 111, 114, 121, 2, 0, 4, 109, 97, 18 | 105, 110, 0, 0, 10, 138, 128, 128, 128, 0, 1, 132, 128, 128, 128, 0, 0, 19 | 65, 42, 11 20 | ]); 21 | 22 | const wasmModule = new WebAssembly.Module(wasmCode); 23 | 24 | const wasmInstance = new WebAssembly.Instance(wasmModule); 25 | 26 | const main = wasmInstance.exports.main as CallableFunction; 27 | console.log(main().toString()); 28 | ``` 29 | 30 | As the code above shows, the following steps need to be performed in order to 31 | load WebAssembly in a JavaScript program: 32 | 33 | 1. Fetching the binary (usually in the form of a `.wasm` file, though we are 34 | using a simple byte array for now) 35 | 2. Compiling the binary into a `WebAssembly.Module` object 36 | 3. Instantiating the WebAssembly module 37 | 38 | For more complex scenarios you will probably want to write in a programming 39 | language that compiles down to WebAssembly instead of hand writing instructions. 40 | A number of languages exist that can do this, such as 41 | [Rust](https://www.rust-lang.org/), [Go](https://golang.org/) or 42 | [AssemblyScript](https://www.assemblyscript.org/). As an example, a Rust program 43 | that compiles to the aforementioned bytes would look something like this: 44 | 45 | ```rust 46 | pub fn main() -> u32 { // u32 stands for an unsigned integer using 32 bits of memory. 47 | 42 48 | } 49 | ``` 50 | 51 | Aside from the methods shown in the preceding example, it is also possible to 52 | use the streaming methods of the WebAssembly API, as will be shown on the next 53 | page. 54 | -------------------------------------------------------------------------------- /runtime/webassembly/wasm_resources.md: -------------------------------------------------------------------------------- 1 | # Helpful Resources 2 | 3 | This page contains some further information that is helpful when using and/or 4 | developing WebAssembly modules. 5 | 6 | ## WebAssembly API 7 | 8 | Further information on all parts of the WebAssembly API can be found on 9 | [MDN](https://developer.mozilla.org/en-US/docs/WebAssembly). 10 | 11 | ## Working with Non-Numeric Types 12 | 13 | The code samples in this chapter only used numeric types in the WebAssembly 14 | modules. To run WebAssembly with more complex types (strings, classes) you will 15 | want to use tools that generate type bindings between JavaScript and the 16 | language used to compile to WebAssembly. 17 | 18 | An example on how to create type bindings between JavaScript and Rust, compiling 19 | it into a binary and calling it from a JavaScript program can be found on 20 | [MDN](https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm). 21 | 22 | If you plan to do a lot of work with Web APIs in Rust+WebAssembly, you may find 23 | the [web_sys](https://rustwasm.github.io/wasm-bindgen/web-sys/index.html) and 24 | [js_sys](https://rustwasm.github.io/wasm-bindgen/contributing/js-sys/index.html) 25 | Rust crates useful. `web_sys` contains bindings to most of the Web APIs that are 26 | available in Deno, while `js_sys` provides bindings to JavaScript's standard, 27 | built-in objects. 28 | 29 | ## Optimization 30 | 31 | For production builds it can be a good idea to perform optimizations on 32 | WebAssembly binaries. If you're mainly serving binaries over networks then 33 | optimizing for size can make a real difference, whereas if you're mainly 34 | executing WebAssembly on a server to perform computationally intensive tasks, 35 | optimizing for speed can be beneficial. You can find a good guide on optimizing 36 | (production) builds 37 | [here](https://rustwasm.github.io/docs/book/reference/code-size.html). In 38 | addition, the 39 | [rust-wasm group](https://rustwasm.github.io/docs/book/reference/tools.html) has 40 | a list of tools that can be used to optimize and manipulate WebAssembly 41 | binaries. 42 | -------------------------------------------------------------------------------- /tools.md: -------------------------------------------------------------------------------- 1 | # Built-In Tooling 2 | 3 | Deno ships with a robust toolchain so you can start building immediately without 4 | needing to setup a disparate set of tooling. 5 | 6 | Deno's modern tooling is categorized below: 7 | 8 | ## Develop 9 | 10 | - [start a new project: `deno init`](./tools/init.md) 11 | - [linter: `deno lint`](./tools/linter.md) 12 | - [formatter: `deno fmt`](./tools/formatter.md) 13 | - [typechecker: `deno check`](./advanced/typescript/overview.md#type-checking) 14 | - [task runner: `deno task`](./tools/task_runner.md) 15 | - [generate documentation: `deno doc`](./tools/documentation_generator.md) 16 | - [inspect dependencies: `deno info`](./tools/dependency_inspector.md) 17 | - [vendor dependencies: `deno vendor`](./tools/vendor.md) 18 | 19 | ## Test 20 | 21 | - [test runner: `deno test`](./basics/testing.md) 22 | - [benchmark: `deno bench`](./tools/benchmarker.md) 23 | 24 | ## Distribute 25 | 26 | - [compile to a single executable: `deno compile`](./tools/compiler.md) 27 | - [installer: `deno install`](./tools/script_installer.md) 28 | -------------------------------------------------------------------------------- /tools/bundler.md: -------------------------------------------------------------------------------- 1 | # WARNING: `deno bundle` has been deprecated and will be removed in some future release. Use [deno_emit](https://github.com/denoland/deno_emit), [esbuild](https://esbuild.github.io/) or [rollup](https://rollupjs.org) instead. 2 | 3 | # Bundling 4 | 5 | `deno bundle [URL]` will output a single JavaScript file for consumption in 6 | Deno, which includes all dependencies of the specified input. For example: 7 | 8 | ```bash 9 | deno bundle https://deno.land/std@0.198.0/examples/colors.ts colors.bundle.js 10 | Bundle https://deno.land/std@0.198.0/examples/colors.ts 11 | Download https://deno.land/std@0.198.0/examples/colors.ts 12 | Download https://deno.land/std@0.198.0/fmt/colors.ts 13 | Emit "colors.bundle.js" (9.83KB) 14 | ``` 15 | 16 | If you omit the out file, the bundle will be sent to `stdout`. 17 | 18 | The bundle can just be run as any other module in Deno would: 19 | 20 | ```bash 21 | deno run colors.bundle.js 22 | ``` 23 | 24 | The output is a self contained ES Module, where any exports from the main module 25 | supplied on the command line will be available. For example, if the main module 26 | looked something like this: 27 | 28 | ```ts, ignore 29 | export { foo } from "./foo.js"; 30 | 31 | export const bar = "bar"; 32 | ``` 33 | 34 | It could be imported like this: 35 | 36 | ```ts, ignore 37 | import { bar, foo } from "./lib.bundle.js"; 38 | ``` 39 | 40 | ## Bundling for the Web 41 | 42 | The output of `deno bundle` is intended for consumption in Deno and not for use 43 | in a web browser or other runtimes. That said, depending on the input it may 44 | work in other environments. 45 | 46 | If you wish to bundle for the web, we recommend other solutions such as 47 | [esbuild](https://esbuild.github.io/). 48 | -------------------------------------------------------------------------------- /tools/compiler.md: -------------------------------------------------------------------------------- 1 | # Compiling Executables 2 | 3 | `deno compile [--output ] ` will compile the script into a 4 | self-contained executable. 5 | 6 | ``` 7 | > deno compile https://examples.deno.land/hello-world.ts 8 | ``` 9 | 10 | If you omit the `OUT` parameter, the name of the executable file will be 11 | inferred. 12 | 13 | ## Flags 14 | 15 | As with [`deno install`](./script_installer.md), the runtime flags used to 16 | execute the script must be specified at compilation time. This includes 17 | permission flags. 18 | 19 | ``` 20 | > deno compile --allow-read --allow-net https://deno.land/std/http/file_server.ts 21 | ``` 22 | 23 | [Script arguments](../getting_started/command_line_interface.md#script-arguments) 24 | can be partially embedded. 25 | 26 | ``` 27 | > deno compile --allow-read --allow-net https://deno.land/std/http/file_server.ts -p 8080 28 | > ./file_server --help 29 | ``` 30 | 31 | ## Dynamic Imports 32 | 33 | By default, statically analyzable dynamic imports (imports that have the string 34 | literal within the `import("...")` call expression) will be included in the 35 | output. 36 | 37 | ```ts, ignore 38 | // calculator.ts and its dependencies will be included in the binary 39 | const calculator = await import("./calculator.ts"); 40 | ``` 41 | 42 | But non-statically analyzable dynamic imports won't: 43 | 44 | ```ts, ignore 45 | const specifier = condition ? "./calc.ts" : "./better_calc.ts"; 46 | const calculator = await import(specifier); 47 | ``` 48 | 49 | To include non-statically analyzable dynamic imports, specify an 50 | `--include ` flag. 51 | 52 | ```shell 53 | deno compile --include calc.ts --include better_calc.ts main.ts 54 | ``` 55 | 56 | ## Workers 57 | 58 | Similarly to non-statically analyzable dynamic imports, code for 59 | [workers](../runtime/workers.md) is not included in the compiled executable by 60 | default. You must use the `--include ` flag to include the worker code. 61 | 62 | ```shell 63 | deno compile --include worker.ts main.ts 64 | ``` 65 | 66 | ## Cross Compilation 67 | 68 | You can compile binaries for other platforms by adding the `--target` CLI flag. 69 | Deno currently supports compiling to Windows x64, macOS x64, macOS ARM and Linux 70 | x64. Use `deno compile --help` to list the full values for each compilation 71 | target. 72 | 73 | ## Unavailable in executables 74 | 75 | - [Web Storage API](../runtime/web_storage_api.md) 76 | -------------------------------------------------------------------------------- /tools/documentation_generator.md: -------------------------------------------------------------------------------- 1 | # Documentation Generator 2 | 3 | `deno doc` followed by a list of one or more source files will print the JSDoc 4 | documentation for each of the module's **exported** members. 5 | 6 | For example, given a file `add.ts` with the contents: 7 | 8 | ```ts 9 | /** 10 | * Adds x and y. 11 | * @param {number} x 12 | * @param {number} y 13 | * @returns {number} Sum of x and y 14 | */ 15 | export function add(x: number, y: number): number { 16 | return x + y; 17 | } 18 | ``` 19 | 20 | Running the Deno `doc` command, prints the function's JSDoc comment to `stdout`: 21 | 22 | ```shell 23 | deno doc add.ts 24 | function add(x: number, y: number): number 25 | Adds x and y. @param {number} x @param {number} y @returns {number} Sum of x and y 26 | ``` 27 | 28 | Use the `--json` flag to output the documentation in JSON format. This JSON 29 | format is consumed by the 30 | [deno doc website](https://github.com/denoland/docland) and is used to generate 31 | module documentation. 32 | -------------------------------------------------------------------------------- /tools/formatter.md: -------------------------------------------------------------------------------- 1 | # Code Formatter 2 | 3 | Deno ships with a built-in code formatter that will auto-format the following 4 | files: 5 | 6 | | File Type | Extension | 7 | | ---------- | ------------------ | 8 | | JavaScript | `.js` | 9 | | TypeScript | `.ts` | 10 | | JSX | `.jsx` | 11 | | TSX | `.tsx` | 12 | | Markdown | `.md`, `.markdown` | 13 | | JSON | `.json` | 14 | | JSONC | `.jsonc` | 15 | 16 | In addition, `deno fmt` can format code snippets in Markdown files. Snippets 17 | must be enclosed in triple backticks and have a language attribute. 18 | 19 | ```shell 20 | # format all supported files in the current directory and subdirectories 21 | deno fmt 22 | # format specific files 23 | deno fmt myfile1.ts myfile2.ts 24 | # format all supported files in specified directory and subdirectories 25 | deno fmt src/ 26 | # check if all the supported files in the current directory and subdirectories are formatted 27 | deno fmt --check 28 | # format stdin and write to stdout 29 | cat file.ts | deno fmt - 30 | ``` 31 | 32 | ## Ignoring Code 33 | 34 | Ignore formatting code by preceding it with a `// deno-fmt-ignore` comment in 35 | TS/JS/JSONC: 36 | 37 | ```ts 38 | // deno-fmt-ignore 39 | export const identity = [ 40 | 1, 0, 0, 41 | 0, 1, 0, 42 | 0, 0, 1, 43 | ]; 44 | ``` 45 | 46 | Or ignore an entire file by adding a `// deno-fmt-ignore-file` comment at the 47 | top of the file. 48 | 49 | In markdown you may use a `` comment or ignore a whole 50 | file with a `` comment. To ignore a section of 51 | markdown, surround the code with `` and 52 | `` comments. 53 | 54 | ## Configuration 55 | 56 | > ℹ️ It is recommended to stick with default options. 57 | 58 | Starting with Deno v1.14 a formatter can be customized using either 59 | [a configuration file](../getting_started/configuration_file.md) or following 60 | CLI flags: 61 | 62 | - `--use-tabs` - Whether to use tabs. Defaults to false (using spaces). 63 | 64 | - `--line-width` - The width of a line the printer will try to stay under. Note 65 | that the printer may exceed this width in certain cases. Defaults to 80. 66 | 67 | - `--indent-width` - The number of characters for an indent. Defaults to 2. 68 | 69 | - `--no-semicolons` - To not use semicolons except where necessary. 70 | 71 | - `--single-quote` - Whether to use single quote. Defaults to false (using 72 | double quote). 73 | 74 | - `--prose-wrap={always,never,preserve}` - Define how prose should be wrapped in 75 | Markdown files. Defaults to "always". 76 | 77 | Note: In Deno versions < 1.31 you will have to prefix these flags with 78 | `options-` (ex. `--options-use-tabs`) 79 | -------------------------------------------------------------------------------- /tools/init.md: -------------------------------------------------------------------------------- 1 | # Starting a new project 2 | 3 | Starting a new project with Deno has always been incredibly simple: you just 4 | need a single file to get going. No need for any configuration files, dependency 5 | manifests, or build scripts. 6 | 7 | Users coming from other ecosystems are often not used to this simplicity - they 8 | often look for a tool to scaffold out a basic project structure to get them 9 | started on the right path. `deno init` subcommand scaffolds a basic Deno 10 | project. 11 | 12 | ```sh 13 | $ deno init 14 | ✅ Project initialized 15 | Run these commands to get started 16 | 17 | // Run the program 18 | deno run main.ts 19 | 20 | // Run the program and watch for file changes 21 | deno task dev 22 | 23 | // Run the tests 24 | deno test 25 | 26 | // Run the benchmarks 27 | deno bench 28 | 29 | $ deno run main.ts 30 | Add 2 + 3 = 5 31 | 32 | $ deno test 33 | Check file:///dev/main_test.ts 34 | running 1 test from main_test.ts 35 | addTest ... ok (6ms) 36 | 37 | ok | 1 passed | 0 failed (29ms) 38 | ``` 39 | 40 | This subcommand will create two files (`main.ts` and `main_test.ts`). These 41 | files provide a basic example of how to write a Deno program and how to write 42 | tests for it. The `main.ts` file exports a `add` function that adds two numbers 43 | together and the `main_test.ts` file contains a test for this function. 44 | 45 | You can also specify an argument to `deno init` to initialize a project in a 46 | specific directory: 47 | 48 | ```sh 49 | $ deno init my_deno_project 50 | ✅ Project initialized 51 | 52 | Run these commands to get started 53 | 54 | cd my_deno_project 55 | 56 | // Run the program 57 | deno run main.ts 58 | 59 | // Run the program and watch for file changes 60 | deno task dev 61 | 62 | // Run the tests 63 | deno test 64 | 65 | // Run the benchmarks 66 | deno bench 67 | ``` 68 | -------------------------------------------------------------------------------- /tools/linter.md: -------------------------------------------------------------------------------- 1 | # Linter 2 | 3 | Deno ships with a built-in code linter for JavaScript and TypeScript. 4 | 5 | ```shell 6 | # lint all JS/TS files in the current directory and subdirectories 7 | deno lint 8 | # lint specific files 9 | deno lint myfile1.ts myfile2.ts 10 | # lint all JS/TS files in specified directory and subdirectories 11 | deno lint src/ 12 | # print result as JSON 13 | deno lint --json 14 | # read from stdin 15 | cat file.ts | deno lint - 16 | ``` 17 | 18 | For more detail, run `deno lint --help`. 19 | 20 | ## Available rules 21 | 22 | For a complete list of supported rules visit 23 | [the deno_lint rule documentation](https://lint.deno.land). 24 | 25 | ## Ignore directives 26 | 27 | ### Files 28 | 29 | To ignore whole file `// deno-lint-ignore-file` directive should placed at the 30 | top of the file: 31 | 32 | ```ts 33 | // deno-lint-ignore-file 34 | 35 | function foo(): any { 36 | // ... 37 | } 38 | ``` 39 | 40 | Ignore directive must be placed before first statement or declaration: 41 | 42 | ```ts, ignore 43 | // Copyright 2020 the Deno authors. All rights reserved. MIT license. 44 | 45 | /** 46 | * Some JS doc 47 | */ 48 | 49 | // deno-lint-ignore-file 50 | 51 | import { bar } from "./bar.js"; 52 | 53 | function foo(): any { 54 | // ... 55 | } 56 | ``` 57 | 58 | You can also ignore certain diagnostics in the whole file 59 | 60 | ```ts 61 | // deno-lint-ignore-file no-explicit-any no-empty 62 | 63 | function foo(): any { 64 | // ... 65 | } 66 | ``` 67 | 68 | ### Diagnostics 69 | 70 | To ignore certain diagnostic `// deno-lint-ignore ` directive should 71 | be placed before offending line. Specifying ignored rule name is required: 72 | 73 | ```ts 74 | // deno-lint-ignore no-explicit-any 75 | function foo(): any { 76 | // ... 77 | } 78 | 79 | // deno-lint-ignore no-explicit-any explicit-function-return-type 80 | function bar(a: any) { 81 | // ... 82 | } 83 | ``` 84 | 85 | ## Configuration 86 | 87 | Starting with Deno v1.14 a linter can be customized using either 88 | [a configuration file](../getting_started/configuration_file.md) or following 89 | CLI flags: 90 | 91 | - `--rules-tags` - List of tag names that will be run. Empty list disables all 92 | tags and will only use rules from `include`. Defaults to "recommended". 93 | 94 | - `--rules-exclude` - List of rule names that will be excluded from configured 95 | tag sets. Even if the same rule is in `include` it will be excluded; in other 96 | words, `--rules-exclude` has higher precedence over `--rules-include`. 97 | 98 | - `--rules-include` - List of rule names that will be run. If the same rule is 99 | in `exclude` it will be excluded. 100 | -------------------------------------------------------------------------------- /tools/script_installer.md: -------------------------------------------------------------------------------- 1 | # Script Installer 2 | 3 | Deno provides `deno install` to easily install and distribute executable code. 4 | 5 | `deno install [OPTIONS...] [URL] [SCRIPT_ARGS...]` will install the script 6 | available at `URL` under the name `EXE_NAME`. 7 | 8 | This command creates a thin, executable shell script which invokes `deno` using 9 | the specified CLI flags and main module. It is placed in the installation root's 10 | `bin` directory. 11 | 12 | Example: 13 | 14 | ```shell 15 | $ deno install --allow-net --allow-read https://deno.land/std@$STD_VERSION/http/file_server.ts 16 | [1/1] Compiling https://deno.land/std@$STD_VERSION/http/file_server.ts 17 | 18 | ✅ Successfully installed file_server. 19 | /Users/deno/.deno/bin/file_server 20 | ``` 21 | 22 | To change the executable name, use `-n`/`--name`: 23 | 24 | ```shell 25 | deno install --allow-net --allow-read -n serve https://deno.land/std@$STD_VERSION/http/file_server.ts 26 | ``` 27 | 28 | The executable name is inferred by default: 29 | 30 | - Attempt to take the file stem of the URL path. The above example would become 31 | 'file_server'. 32 | - If the file stem is something generic like 'main', 'mod', 'index' or 'cli', 33 | and the path has no parent, take the file name of the parent path. Otherwise 34 | settle with the generic name. 35 | - If the resulting name has an '@...' suffix, strip it. 36 | 37 | To change the installation root, use `--root`: 38 | 39 | ```shell 40 | deno install --allow-net --allow-read --root /usr/local https://deno.land/std@$STD_VERSION/http/file_server.ts 41 | ``` 42 | 43 | The installation root is determined, in order of precedence: 44 | 45 | - `--root` option 46 | - `DENO_INSTALL_ROOT` environment variable 47 | - `$HOME/.deno` 48 | 49 | These must be added to the path manually if required. 50 | 51 | ```shell 52 | echo 'export PATH="$HOME/.deno/bin:$PATH"' >> ~/.bashrc 53 | ``` 54 | 55 | You must specify permissions that will be used to run the script at installation 56 | time. 57 | 58 | ```shell 59 | deno install --allow-net --allow-read https://deno.land/std@$STD_VERSION/http/file_server.ts -p 8080 60 | ``` 61 | 62 | The above command creates an executable called `file_server` that runs with 63 | network and read permissions and binds to port 8080. 64 | 65 | For good practice, use the [`import.meta.main`](../examples/module_metadata.md) 66 | idiom to specify the entry point in an executable script. 67 | 68 | Example: 69 | 70 | 71 | 72 | ```ts 73 | // https://example.com/awesome/cli.ts 74 | async function myAwesomeCli(): Promise { 75 | // -- snip -- 76 | } 77 | 78 | if (import.meta.main) { 79 | myAwesomeCli(); 80 | } 81 | ``` 82 | 83 | When you create an executable script make sure to let users know by adding an 84 | example installation command to your repository: 85 | 86 | ```shell 87 | # Install using deno install 88 | 89 | $ deno install -n awesome_cli https://example.com/awesome/cli.ts 90 | ``` 91 | 92 | ## Uninstall 93 | 94 | You can uninstall the script with `deno uninstall` command. 95 | 96 | ```shell 97 | $ deno uninstall file_server 98 | deleted /Users/deno/.deno/bin/file_server 99 | ✅ Successfully uninstalled file_server 100 | ``` 101 | 102 | See `deno uninstall -h` for more details. 103 | -------------------------------------------------------------------------------- /tools/vendor.md: -------------------------------------------------------------------------------- 1 | # Vendoring Dependencies 2 | 3 | `deno vendor ...` will download all remote dependencies of the 4 | specified modules into a local `vendor` folder. For example: 5 | 6 | ```shell 7 | # Vendor the remote dependencies of main.ts 8 | $ deno vendor main.ts 9 | 10 | # Example file system tree 11 | $ tree 12 | . 13 | ├── main.ts 14 | └── vendor 15 | ├── deno.land 16 | ├── import_map.json 17 | └── raw.githubusercontent.com 18 | 19 | # Check the directory into source control 20 | $ git add -u vendor 21 | $ git commit 22 | ``` 23 | 24 | To then use the vendored dependencies in your program, just add 25 | `--import-map=vendor/import_map.json` to your Deno invocations. You can also add 26 | `--no-remote` to your invocation to completely disable fetching of remote 27 | modules to ensure it's using the modules in the vendor directory. 28 | 29 | ```shell 30 | deno run --no-remote --import-map=vendor/import_map.json main.ts 31 | ``` 32 | 33 | Note that you may specify multiple modules and remote modules when vendoring. 34 | 35 | ```shell 36 | deno vendor main.ts test.deps.ts https://deno.land/std/path/mod.ts 37 | ``` 38 | 39 | Run `deno vendor --help` for more details. 40 | -------------------------------------------------------------------------------- /typos.toml: -------------------------------------------------------------------------------- 1 | [default.extend-words] 2 | Linke = "Linke" # LinkeDOM --------------------------------------------------------------------------------