├── .gitignore ├── images ├── deno3.png ├── debugger1.jpg ├── debugger2.jpg ├── debugger3.jpg ├── debugger4.jpg ├── debugger5.jpg ├── debugger7.jpg ├── jb-ide-debug.png ├── private-pat.png ├── private-github-new-token.png ├── workspace_folder_config.png └── private-github-token-display.png ├── getting_started ├── typescript.md ├── configuration_file.md ├── installation.md ├── debugging_your_code.md ├── command_line_interface.md ├── first_steps.md └── permissions.md ├── runtime ├── compiler_apis.md ├── stability.md ├── web_storage_api.md ├── location_api.md ├── program_lifecycle.md └── ffi_api.md ├── .github ├── import_map.json └── workflows │ ├── ci.yml │ └── main.yml ├── linking_to_external_code ├── proxies.md ├── import_maps.md ├── reloading_modules.md ├── integrity_checking.md └── private.md ├── typescript.md ├── embedding_deno.md ├── jsx_dom.md ├── README.md ├── node ├── dnt.md ├── cheatsheet.md ├── faqs.md ├── import_maps.md ├── compatibility_mode.md └── std_node.md ├── getting_started.md ├── webassembly.md ├── help.md ├── language_server.md ├── tools.md ├── examples.md ├── tools ├── documentation_generator.md ├── vendor.md ├── compiler.md ├── bundler.md ├── linter.md ├── formatter.md ├── script_installer.md └── dependency_inspector.md ├── runtime.md ├── LICENSE ├── contributing ├── release_schedule.md ├── architecture.md ├── building_from_source.md └── web_platform_tests.md ├── testing ├── documentation.md ├── coverage.md └── sanitizers.md ├── examples ├── unix_cat.md ├── file_system_events.md ├── tcp_echo.md ├── hello_world.md ├── module_metadata.md ├── manage_dependencies.md ├── http_server.md ├── os_signals.md ├── fetch_data.md ├── read_write_files.md ├── import_export.md ├── file_server.md └── subprocess.md ├── publishing.md ├── webassembly ├── using_streaming_wasm.md ├── wasm_resources.md └── using_wasm.md ├── jsx_dom ├── twind.md ├── css.md ├── deno_dom.md ├── jsdom.md ├── linkedom.md ├── overview.md └── jsx.md ├── typescript └── migration.md ├── standard_library.md ├── introduction.md ├── node.md ├── linking_to_external_code.md ├── vscode_deno └── testing_api.md ├── toc.json └── contributing.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /images/deno3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/deno3.png -------------------------------------------------------------------------------- /images/debugger1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/debugger1.jpg -------------------------------------------------------------------------------- /images/debugger2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/debugger2.jpg -------------------------------------------------------------------------------- /images/debugger3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/debugger3.jpg -------------------------------------------------------------------------------- /images/debugger4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/debugger4.jpg -------------------------------------------------------------------------------- /images/debugger5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/debugger5.jpg -------------------------------------------------------------------------------- /images/debugger7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/debugger7.jpg -------------------------------------------------------------------------------- /images/jb-ide-debug.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/jb-ide-debug.png -------------------------------------------------------------------------------- /images/private-pat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/private-pat.png -------------------------------------------------------------------------------- /images/private-github-new-token.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/private-github-new-token.png -------------------------------------------------------------------------------- /images/workspace_folder_config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/workspace_folder_config.png -------------------------------------------------------------------------------- /images/private-github-token-display.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adaptive/manual/main/images/private-github-token-display.png -------------------------------------------------------------------------------- /getting_started/typescript.md: -------------------------------------------------------------------------------- 1 | ## Using TypeScript 2 | 3 | > ℹ️ This section has been moved to 4 | > [Using TypeScript Chapter](../typescript.md). 5 | -------------------------------------------------------------------------------- /runtime/compiler_apis.md: -------------------------------------------------------------------------------- 1 | ## Compiler APIs 2 | 3 | > ℹ️ This section has been moved to 4 | > [TypeScript Runtime APIs](../typescript/runtime.md). 5 | -------------------------------------------------------------------------------- /.github/import_map.json: -------------------------------------------------------------------------------- 1 | { 2 | "imports": { 3 | "https://deno.land/std@$STD_VERSION/": "https://deno.land/std/", 4 | "jsdom": "https://esm.sh/jsdom" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /linking_to_external_code/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 | -------------------------------------------------------------------------------- /typescript.md: -------------------------------------------------------------------------------- 1 | # Using TypeScript 2 | 3 | In this chapter we will discuss: 4 | 5 | - [Overview of TypeScript in Deno](./typescript/overview.md) 6 | - [Configuring TypeScript in Deno](./typescript/configuration.md) 7 | - [Types and Type Declarations](./typescript/types.md) 8 | - [Migrating to/from JavaScript](./typescript/migration.md) 9 | - [Runtime compiler APIs](./typescript/runtime.md) 10 | - [FAQs about TypeScript in Deno](./typescript/faqs.md) 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /jsx_dom.md: -------------------------------------------------------------------------------- 1 | # Using JSX and the DOM 2 | 3 | In this chapter we will discuss: 4 | 5 | - [Overview of JSX and DOM in Deno](./jsx_dom/overview.md) 6 | - [Configuring JSX in Deno](./jsx_dom/jsx.md) 7 | - [Using LinkeDOM with Deno](./jsx_dom/LinkeDOM.md) 8 | - [Using deno-dom with Deno](./deno_dom.md) 9 | - [Using JSDOM with Deno](./jsx_dom/jsdom.md) 10 | - [Parsing and stringifying CSS](./jsx_dom/css.md) 11 | - [Using Twind with Deno](./jsx_dom/twind.md) 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deno manual 2 | 3 | This repository is the official documentation for Deno. 4 | 5 | Manual is available at: https://deno.land/manual 6 | 7 | ## Contributing 8 | 9 | When opening a PR, make sure the code is formatted correctly. To format the 10 | code: 11 | 12 | 1. Install Deno (https://deno.land/#installation) 13 | 2. Run `deno fmt` at the root of this repository 14 | 15 | Before creating new pages, open an issue and discuss the proposed changes. 16 | -------------------------------------------------------------------------------- /node/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 | -------------------------------------------------------------------------------- /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 | - [Writing our own script](./getting_started/first_steps.md) 9 | - [Command line interface](./getting_started/command_line_interface.md) 10 | - [Understanding permissions](./getting_started/permissions.md) 11 | - [Debugging your code](./getting_started/debugging_your_code.md) 12 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /help.md: -------------------------------------------------------------------------------- 1 | # Where To Get Help 2 | 3 | Stuck? Lost? Get Help from the Community. 4 | 5 | ### [Stack Overflow](https://stackoverflow.com/questions/tagged/deno) 6 | 7 | Stack Overflow is a popular forum to ask code-level questions or if you’re stuck 8 | with a specific error. 9 | [ask your own!](https://stackoverflow.com/questions/ask?tags=deno) 10 | 11 | ### [Community Discord](https://discord.gg/deno) 12 | 13 | Ask questions and chat with community members in real-time. 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 | -------------------------------------------------------------------------------- /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](./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 | -------------------------------------------------------------------------------- /.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 | format: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v3 15 | 16 | - name: Set up Deno 17 | uses: denoland/setup-deno@v1.0.0 18 | 19 | - name: Format 20 | run: deno fmt --check 21 | 22 | type-check: 23 | runs-on: ubuntu-latest 24 | steps: 25 | - name: Checkout repository 26 | uses: actions/checkout@v2 27 | 28 | - name: Set up Deno 29 | uses: denoland/setup-deno@v1.0.0 30 | 31 | - name: Type-check Deno manual 32 | run: deno test --doc --unstable --import-map=.github/import_map.json --no-check=remote 33 | -------------------------------------------------------------------------------- /tools.md: -------------------------------------------------------------------------------- 1 | # Built-in tooling 2 | 3 | Deno provides some built-in tooling that is useful when working with JavaScript 4 | and TypeScript: 5 | 6 | - [benchmarker (`deno bench`)](./tools/benchmarker.md) 7 | - [bundler (`deno bundle`)](./tools/bundler.md) 8 | - [compiling executables (`deno compile`)](./tools/compiler.md) 9 | - [installer (`deno install`)](./tools/script_installer.md) 10 | - [dependency inspector (`deno info`)](./tools/dependency_inspector.md) 11 | - [documentation generator (`deno doc`)](./tools/documentation_generator.md) 12 | - [formatter (`deno fmt`)](./tools/formatter.md) 13 | - [linter (`deno lint`)](./tools/linter.md) 14 | - [repl (`deno repl`)](./tools/repl.md) 15 | - [task runner (`deno task`)](./tools/task_runner.md) 16 | - [test runner (`deno test`)](./testing.md) 17 | - [vendoring dependencies (`deno vendor`)](./tools/vendor.md) 18 | -------------------------------------------------------------------------------- /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 | - [Import and export modules](./examples/import_export.md) 10 | - [Manage dependencies](./examples/manage_dependencies.md) 11 | - [Fetch data](./examples/fetch_data.md) 12 | - [Read and write files](./examples/read_write_files.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /linking_to_external_code/import_maps.md: -------------------------------------------------------------------------------- 1 | ## Import maps 2 | 3 | Deno supports [import maps](https://github.com/WICG/import-maps). 4 | 5 | You can use import maps with the `--import-map=` CLI flag. 6 | 7 | Example: 8 | 9 | **import_map.json** 10 | 11 | ```json 12 | { 13 | "imports": { 14 | "fmt/": "https://deno.land/std@$STD_VERSION/fmt/" 15 | } 16 | } 17 | ``` 18 | 19 | **color.ts** 20 | 21 | ```ts, ignore 22 | import { red } from "fmt/colors.ts"; 23 | 24 | console.log(red("hello world")); 25 | ``` 26 | 27 | Then: 28 | 29 | ```shell 30 | $ deno run --import-map=import_map.json color.ts 31 | ``` 32 | 33 | To use your project root for absolute imports: 34 | 35 | **import_map.json** 36 | 37 | ```jsonc 38 | { 39 | "imports": { 40 | "/": "./", 41 | "./": "./" 42 | } 43 | } 44 | ``` 45 | 46 | **main.ts** 47 | 48 | ```ts, ignore 49 | import { MyUtil } from "/util.ts"; 50 | ``` 51 | 52 | This causes import specifiers starting with `/` to be resolved relative to the 53 | import map's URL or file path. 54 | -------------------------------------------------------------------------------- /.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-20.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 -------------------------------------------------------------------------------- /runtime.md: -------------------------------------------------------------------------------- 1 | # Runtime 2 | 3 | Documentation for all runtime functions (Web APIs + `Deno` global) can be found 4 | on [`doc.deno.land/deno/stable`](https://doc.deno.land/deno/stable@$CLI_VERSION) 5 | with _unstable_ APIs which are enabled via the `--unstable` flag at 6 | [`doc.deno.land/deno/unstable`](https://doc.deno.land/deno/unstable@$CLI_VERSION). 7 | 8 | ## Web Platform APIs 9 | 10 | For APIs where a web standard already exists, like `fetch` for HTTP requests, 11 | Deno uses these rather than inventing a new proprietary API. 12 | 13 | For more details, view the chapter on 14 | [Web Platform APIs](./runtime/web_platform_apis.md). 15 | 16 | ## `Deno` global 17 | 18 | All APIs that are not web standard are contained in the global `Deno` namespace. 19 | It has the APIs for reading from files, opening TCP sockets, 20 | [serving HTTP](./runtime/http_server_apis.md), and executing subprocesses, etc. 21 | 22 | The TypeScript definitions for the Deno namespaces can be found in the 23 | [`lib.deno.ns.d.ts`](https://github.com/denoland/deno/blob/$CLI_VERSION/cli/dts/lib.deno.ns.d.ts) 24 | file. 25 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /linking_to_external_code/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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://deno.land/std/examples/welcome.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 | ### Cross Compilation 32 | 33 | You can compile binaries for other platforms by adding the `--target` CLI flag. 34 | Deno currently supports compiling to Windows x64, macOS x64, macOS ARM and Linux 35 | x64. Use `deno compile --help` to list the full values for each compilation 36 | target. 37 | -------------------------------------------------------------------------------- /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 | There are usually two or three patch releases (done weekly) after a minor 7 | releases; after that a merge window for new features opens for the upcoming 8 | minor release. 9 | 10 | The release dates for the upcoming minor releases are: 11 | 12 | - 1.20.0: March 16, 2022 13 | - 1.21.0: April 20, 2022 14 | - 1.22.0: May 18, 2022 15 | 16 | Stable releases can be found on the 17 | [GitHub releases page](https://github.com/denoland/deno/releases). 18 | 19 | ### Canary channel 20 | 21 | In addition to the stable channel described above, canaries are released 22 | multiple times daily (for each commit on main). You can upgrade to the latest 23 | canary release by running: 24 | 25 | ``` 26 | deno upgrade --canary 27 | ``` 28 | 29 | To update to a specific canary, pass the commit hash in the `--version` option: 30 | 31 | ``` 32 | deno upgrade --canary --version=973af61d8bb03c1709f61e456581d58386ed4952 33 | ``` 34 | 35 | To switch back to the stable channel, run `deno upgrade`. 36 | 37 | Canaries can be downloaded from https://dl.deno.land. 38 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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](https://doc.deno.land/deno/stable/~/Deno.args) accesses the 7 | command line arguments. 8 | - [Deno.open](https://doc.deno.land/deno/stable/~/Deno.open) is used to get a 9 | handle to a file. 10 | - [copy](https://doc.deno.land/https://deno.land/std@$STD_VERSION/streams/conversion.ts/~/copy) 11 | is used to transfer data from the file to the output stream. 12 | - Files should be closed when you are finished with them 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 | import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; 25 | for (const filename of Deno.args) { 26 | const file = await Deno.open(filename); 27 | await copy(file, Deno.stdout); 28 | file.close(); 29 | } 30 | ``` 31 | 32 | To run the program: 33 | 34 | ```shell 35 | deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd 36 | ``` 37 | -------------------------------------------------------------------------------- /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 editor 22 | or 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 | ## Publishing Deno modules for Node.js 29 | 30 | See [dnt - Deno to Node Transform](./node/dnt.md). 31 | -------------------------------------------------------------------------------- /examples/file_system_events.md: -------------------------------------------------------------------------------- 1 | # File system events 2 | 3 | ## Concepts 4 | 5 | - Use [Deno.watchFs](https://doc.deno.land/deno/stable/~/Deno.watchFs) to watch 6 | for file system events. 7 | - Results may vary between operating systems. 8 | 9 | ## Example 10 | 11 | To poll for file system events in the current directory: 12 | 13 | ```ts 14 | /** 15 | * watcher.ts 16 | */ 17 | const watcher = Deno.watchFs("."); 18 | for await (const event of watcher) { 19 | console.log(">>>> event", event); 20 | // Example event: { kind: "create", paths: [ "/home/alice/deno/foo.txt" ] } 21 | } 22 | ``` 23 | 24 | Run with: 25 | 26 | ```shell 27 | deno run --allow-read watcher.ts 28 | ``` 29 | 30 | Now try adding, removing and modifying files in the same directory as 31 | `watcher.ts`. 32 | 33 | Note that the exact ordering of the events can vary between operating systems. 34 | This feature uses different syscalls depending on the platform: 35 | 36 | - Linux: [inotify](https://man7.org/linux/man-pages/man7/inotify.7.html) 37 | - macOS: 38 | [FSEvents](https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html) 39 | - Windows: 40 | [ReadDirectoryChangesW](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw) 41 | -------------------------------------------------------------------------------- /examples/tcp_echo.md: -------------------------------------------------------------------------------- 1 | # TCP echo server 2 | 3 | ## Concepts 4 | 5 | - Listening for TCP port connections with 6 | [Deno.listen](https://doc.deno.land/deno/stable/~/Deno.listen). 7 | - Use 8 | [copy](https://doc.deno.land/https://deno.land/std@$STD_VERSION/streams/conversion.ts/~/copy) 9 | to take inbound data and redirect it to be outbound data. 10 | 11 | ## Example 12 | 13 | This is an example of a server which accepts connections on port 8080, and 14 | returns to the client anything it sends. 15 | 16 | ```ts 17 | /** 18 | * echo_server.ts 19 | */ 20 | import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; 21 | const listener = Deno.listen({ port: 8080 }); 22 | console.log("listening on 0.0.0.0:8080"); 23 | for await (const conn of listener) { 24 | copy(conn, conn).finally(() => conn.close()); 25 | } 26 | ``` 27 | 28 | Run with: 29 | 30 | ```shell 31 | deno run --allow-net echo_server.ts 32 | ``` 33 | 34 | To test it, try sending data to it with 35 | [netcat](https://en.wikipedia.org/wiki/Netcat) (Linux/MacOS only). Below 36 | `'hello world'` is sent over the connection, which is then echoed back to the 37 | user: 38 | 39 | ```shell 40 | $ nc localhost 8080 41 | hello world 42 | hello world 43 | ``` 44 | 45 | Like the [cat.ts example](./unix_cat.md), the `copy()` function here also does 46 | not make unnecessary memory copies. It receives a packet from the kernel and 47 | sends back, without further complexity. 48 | -------------------------------------------------------------------------------- /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/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/) are not yet stable. We 29 | currently version the standard modules differently from the CLI to reflect this. 30 | Note that unlike the `Deno` namespace, the use of the standard modules do not 31 | require the `--unstable` flag (unless the standard module itself makes use of an 32 | unstable Deno feature). 33 | -------------------------------------------------------------------------------- /tools/bundler.md: -------------------------------------------------------------------------------- 1 | ## Bundling 2 | 3 | `deno bundle [URL]` will output a single JavaScript file, which includes all 4 | dependencies of the specified input. For example: 5 | 6 | ```bash 7 | deno bundle https://deno.land/std@$STD_VERSION/examples/colors.ts colors.bundle.js 8 | Bundle https://deno.land/std@$STD_VERSION/examples/colors.ts 9 | Download https://deno.land/std@$STD_VERSION/examples/colors.ts 10 | Download https://deno.land/std@$STD_VERSION/fmt/colors.ts 11 | Emit "colors.bundle.js" (9.83KB) 12 | ``` 13 | 14 | If you omit the out file, the bundle will be sent to `stdout`. 15 | 16 | The bundle can just be run as any other module in Deno would: 17 | 18 | ```bash 19 | deno run colors.bundle.js 20 | ``` 21 | 22 | The output is a self contained ES Module, where any exports from the main module 23 | supplied on the command line will be available. For example, if the main module 24 | looked something like this: 25 | 26 | ```ts, ignore 27 | export { foo } from "./foo.js"; 28 | 29 | export const bar = "bar"; 30 | ``` 31 | 32 | It could be imported like this: 33 | 34 | ```ts, ignore 35 | import { bar, foo } from "./lib.bundle.js"; 36 | ``` 37 | 38 | Bundles can also be loaded in the web browser. The bundle is a self-contained ES 39 | module, and so the attribute of `type` must be set to `"module"`. For example: 40 | 41 | ```html 42 | 43 | ``` 44 | 45 | Or you could import it into another ES module to consume: 46 | 47 | ```html 48 | 51 | ``` 52 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /getting_started/configuration_file.md: -------------------------------------------------------------------------------- 1 | # Configuration file 2 | 3 | Deno supports configuration file that allows to customize built-in TypeScript 4 | compiler, formatter and linter. 5 | 6 | To tell Deno to use the configuration file pass `--config path/to/file.json` 7 | flag. 8 | 9 | Note that using a configuration file is not required now, and will not be 10 | required in the future. Deno still works best with the default options and no 11 | configuration file. All options specified in the configuration file can also be 12 | set using command line flags (for example `--options-use-tabs` for `deno fmt`). 13 | Using the configuration file should be considered an "as needed" feature, not 14 | something every user should be reaching to as the first thing when setting up a 15 | project. 16 | 17 | The configuration file supports `.json` and `.jsonc` extensions. We recommend to 18 | use `deno.json` or `deno.jsonc` as a file name, as an automatic lookup of this 19 | file is planned for the upcoming releases. 20 | 21 | ## Example 22 | 23 | ```json 24 | { 25 | "compilerOptions": { 26 | "allowJs": true, 27 | "lib": ["deno.window"], 28 | "strict": true 29 | }, 30 | "lint": { 31 | "files": { 32 | "include": ["src/"], 33 | "exclude": ["src/testdata/"] 34 | }, 35 | "rules": { 36 | "tags": ["recommended"], 37 | "include": ["ban-untagged-todo"], 38 | "exclude": ["no-unused-vars"] 39 | } 40 | }, 41 | "fmt": { 42 | "files": { 43 | "include": ["src/"], 44 | "exclude": ["src/testdata/"] 45 | }, 46 | "options": { 47 | "useTabs": true, 48 | "lineWidth": 80, 49 | "indentWidth": 4, 50 | "singleQuote": true, 51 | "proseWrap": "preserve" 52 | } 53 | } 54 | } 55 | ``` 56 | 57 | ## JSON schema 58 | 59 | A JSON schema file is available for editors to provide autocomplete. The file is 60 | versioned and available at: 61 | https://deno.land/x/deno/cli/schemas/config-file.v1.json 62 | -------------------------------------------------------------------------------- /node/cheatsheet.md: -------------------------------------------------------------------------------- 1 | ## Node -> Deno cheatsheet 2 | 3 | | Node | Deno | 4 | | -------------------------------------- | ---------------------------------------------- | 5 | | `npm i -g` | `deno install` | 6 | | `npm i` / `npm install` | _n/a_ ¹ | 7 | | `npm run` | `deno run` | 8 | | `eslint` | `deno lint` | 9 | | `prettier` | `deno fmt` | 10 | | `rollup` / `webpack` / etc | `deno bundle` | 11 | | `package.json` | `deno.json` / `deno.jsonc` / `import_map.json` | 12 | | `tsc` | _n/a; tsc is built-in_ ² | 13 | | `typedoc` | `deno doc` | 14 | | `jest` / `ava` / `mocha` / `tap` / etc | `deno test` | 15 | | `nodemon` | `deno run/lint/test --watch` | 16 | | `nexe` / `pkg` | `deno compile` | 17 | | `npm explain` | `deno info` | 18 | | `nvm` / `n` / `fnm` | `deno upgrade` | 19 | | `tsserver` | `deno lsp` | 20 | | `nyc` / `c8` / `istanbul` | `deno coverage` | 21 | | benchmarks | `deno bench` | 22 | 23 | ¹ See [Linking to external code](../linking_to_external_code.md), the runtime 24 | downloads and caches the code on first use. 25 | 26 | ² Type checking happens automatically, TypeScript compiler is built into the 27 | `deno` binary. 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /node/faqs.md: -------------------------------------------------------------------------------- 1 | ## Frequently asked questions 2 | 3 | ### Getting errors when type checking like `cannot find namespace NodeJS` 4 | 5 | One of the modules you are using has type definitions that depend upon the 6 | NodeJS global namespace, but those types don't include the NodeJS global 7 | namespace in their types. 8 | 9 | The quickest fix is to skip type checking. You can do this by using the 10 | `--no-check` flag. 11 | 12 | Skipping type checking might not be acceptable though. You could try to load the 13 | Node types yourself. For example from UNPKG it would look something like this: 14 | 15 | ```ts, ignore 16 | import type {} from "https://unpkg.com/@types/node/index.d.ts"; 17 | ``` 18 | 19 | Or from esm.sh: 20 | 21 | ```ts, ignore 22 | import type {} from "https://esm.sh/@types/node/index.d.ts"; 23 | ``` 24 | 25 | Or from Skypack: 26 | 27 | ```ts, ignore 28 | import type {} from "https://cdn.skypack.dev/@types/node/index.d.ts"; 29 | ``` 30 | 31 | You could also try to provide only specifically what the 3rd party package is 32 | missing. For example the package `@aws-sdk/client-dynamodb` has a dependency on 33 | the `NodeJS.ProcessEnv` type in its type definitions. In one of the modules of 34 | your project that imports it as a dependency, you could put something like this 35 | in there which will solve the problem: 36 | 37 | ```ts 38 | declare global { 39 | namespace NodeJS { 40 | type ProcessEnv = Record; 41 | } 42 | } 43 | ``` 44 | 45 | ### Getting type errors like cannot find `document` or `HTMLElement` 46 | 47 | The library you are using has dependencies on the DOM. This is common for 48 | packages that are designed to run in a browser as well as server-side. By 49 | default, Deno only includes the libraries that are directly supported. Assuming 50 | the package properly identifies what environment it is running in at runtime it 51 | is "safe" to use the DOM libraries to type check the code. For more information 52 | on this, check out the 53 | [Targeting Deno and the Browser](../typescript/configuration.md#targeting-deno-and-the-browser) 54 | section of the manual. 55 | -------------------------------------------------------------------------------- /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](../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/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 8 | [import.meta.main](https://doc.deno.land/deno/stable/~/ImportMeta#main) will 9 | let you know if the current module is the program entry point. 10 | - The string 11 | [import.meta.url](https://doc.deno.land/deno/stable/~/ImportMeta#url) will 12 | give you the URL of the current module. 13 | - The string 14 | [Deno.mainModule](https://doc.deno.land/deno/stable/~/Deno.mainModule) will 15 | give you the URL of the main module entry point, i.e. the module invoked by 16 | the deno runtime. 17 | 18 | ## Example 19 | 20 | The example below uses two modules to show the difference between 21 | `import.meta.url`, `import.meta.main` and `Deno.mainModule`. In this example, 22 | `module_a.ts` is the main module entry point: 23 | 24 | ```ts 25 | /** 26 | * module_b.ts 27 | */ 28 | export function outputB() { 29 | console.log("Module B's import.meta.url", import.meta.url); 30 | console.log("Module B's mainModule url", Deno.mainModule); 31 | console.log( 32 | "Is module B the main module via import.meta.main?", 33 | import.meta.main, 34 | ); 35 | } 36 | ``` 37 | 38 | ```ts, ignore 39 | /** 40 | * module_a.ts 41 | */ 42 | import { outputB } from "./module_b.ts"; 43 | 44 | function outputA() { 45 | console.log("Module A's import.meta.url", import.meta.url); 46 | console.log("Module A's mainModule url", Deno.mainModule); 47 | console.log( 48 | "Is module A the main module via import.meta.main?", 49 | import.meta.main, 50 | ); 51 | } 52 | 53 | outputA(); 54 | console.log(""); 55 | outputB(); 56 | ``` 57 | 58 | If `module_a.ts` is located in `/home/alice/deno` then the output of 59 | `deno run --allow-read module_a.ts` is: 60 | 61 | ``` 62 | Module A's import.meta.url file:///home/alice/deno/module_a.ts 63 | Module A's mainModule url file:///home/alice/deno/module_a.ts 64 | Is module A the main module via import.meta.main? true 65 | 66 | Module B's import.meta.url file:///home/alice/deno/module_b.ts 67 | Module B's mainModule url file:///home/alice/deno/module_a.ts 68 | Is module B the main module via import.meta.main? false 69 | ``` 70 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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@0.132.0/testing/asserts.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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. If the same rule is in `include` it will be run. 96 | 97 | - `--rules-include` - List of rule names that will be run. Even if the same rule 98 | is in `exclude` it will be run. 99 | -------------------------------------------------------------------------------- /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)](architecture#resources) | 10 | | Scheduler | Tokio | 11 | | Userland: libc++ / glib / boost | https://deno.land/std/ | 12 | | /proc/\$\$/stat | [Deno.metrics()](architecture#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 | -------------------------------------------------------------------------------- /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 [Linking to external code](../linking_to_external_code.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](./import_export.md). But in this case instead 48 | of the Ramda module being referenced directly it is referenced by proxy using a 49 | 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 | -------------------------------------------------------------------------------- /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 | - `--options-use-tabs` - Whether to use tabs. Defaults to false (using spaces). 63 | 64 | - `--options-line-width` - The width of a line the printer will try to stay 65 | under. Note that the printer may exceed this width in certain cases. Defaults 66 | to 80. 67 | 68 | - `--options-indent-width` - The number of characters for an indent. Defaults 69 | to 2. 70 | 71 | - `--options-single-quote` - Whether to use single quote. Defaults to false 72 | (using double quote). 73 | 74 | - `--options-prose-wrap={always,never,preserve}` - Define how prose should be 75 | wrapped in Markdown files. Defaults to "always". 76 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | iwr https://deno.land/x/install/install.ps1 -useb | iex 24 | ``` 25 | 26 | Using [Scoop](https://scoop.sh/) (Windows): 27 | 28 | ```shell 29 | scoop install deno 30 | ``` 31 | 32 | Using [Chocolatey](https://chocolatey.org/packages/deno) (Windows): 33 | 34 | ```shell 35 | choco install deno 36 | ``` 37 | 38 | Using [Homebrew](https://formulae.brew.sh/formula/deno) (macOS): 39 | 40 | ```shell 41 | brew install deno 42 | ``` 43 | 44 | Using [Nix](https://nixos.org/download.html) (macOS and Linux): 45 | 46 | ```shell 47 | nix-shell -p deno 48 | ``` 49 | 50 | Build and install from source using [Cargo](https://crates.io/crates/deno): 51 | 52 | ```shell 53 | cargo install deno --locked 54 | ``` 55 | 56 | Deno binaries can also be installed manually, by downloading a zip file at 57 | [github.com/denoland/deno/releases](https://github.com/denoland/deno/releases). 58 | These packages contain just a single executable file. You will have to set the 59 | executable bit on macOS and Linux. 60 | 61 | ### Docker 62 | 63 | For more information and instructions on the official Docker images: 64 | [https://github.com/denoland/deno_docker](https://github.com/denoland/deno_docker) 65 | 66 | ### Testing your installation 67 | 68 | To test your installation, run `deno --version`. If this prints the Deno version 69 | to the console the installation was successful. 70 | 71 | Use `deno help` to see help text documenting Deno's flags and usage. Get a 72 | detailed guide on the CLI [here](./command_line_interface.md). 73 | 74 | ### Updating 75 | 76 | To update a previously installed version of Deno, you can run: 77 | 78 | ```shell 79 | deno upgrade 80 | ``` 81 | 82 | This will fetch the latest release from 83 | [github.com/denoland/deno/releases](https://github.com/denoland/deno/releases), 84 | unzip it, and replace your current executable with it. 85 | 86 | You can also use this utility to install a specific version of Deno: 87 | 88 | ```shell 89 | deno upgrade --version 1.0.1 90 | ``` 91 | 92 | ### Building from source 93 | 94 | Information about how to build from source can be found in the 95 | [`Contributing`](../contributing/building_from_source.md) chapter. 96 | -------------------------------------------------------------------------------- /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 | ## Sample web server 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( 40 | "user-agent", 41 | ) ?? "Unknown" 42 | }`; 43 | // The requestEvent's `.respondWith()` method is how we send the response 44 | // back to the client. 45 | requestEvent.respondWith( 46 | new Response(body, { 47 | status: 200, 48 | }), 49 | ); 50 | } 51 | } 52 | ``` 53 | 54 | Then run this with: 55 | 56 | ```shell 57 | deno run --allow-net webserver.ts 58 | ``` 59 | 60 | Then navigate to `http://localhost:8080/` in a browser. 61 | 62 | ### Using the `std/http` library 63 | 64 | > ℹ️ Since 65 | > [the stabilization of _native_ HTTP bindings in 66 | `^1.13.x`](https://deno.com/blog/v1.13#stabilize-native-http-server-api), 67 | > std/http now supports a _native_ HTTP server from ^0.107.0. The legacy server 68 | > module was removed in 0.117.0. 69 | 70 | **webserver.ts**: 71 | 72 | ```ts 73 | import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; 74 | 75 | const port = 8080; 76 | 77 | const handler = (request: Request): Response => { 78 | let body = "Your user-agent is:\n\n"; 79 | body += request.headers.get("user-agent") || "Unknown"; 80 | 81 | return new Response(body, { status: 200 }); 82 | }; 83 | 84 | console.log(`HTTP webserver running. Access it at: http://localhost:8080/`); 85 | await serve(handler, { port }); 86 | ``` 87 | 88 | Then run this with: 89 | 90 | ```shell 91 | deno run --allow-net webserver.ts 92 | ``` 93 | -------------------------------------------------------------------------------- /runtime/program_lifecycle.md: -------------------------------------------------------------------------------- 1 | ## Program lifecycle 2 | 3 | Deno supports browser compatible lifecycle events: `load` and `unload`. You can 4 | use these events to provide setup and cleanup code in your program. 5 | 6 | Listeners for `load` events can be asynchronous and will be awaited. Listeners 7 | for `unload` events need to be synchronous. Both events cannot be cancelled. 8 | 9 | Example: 10 | 11 | **main.ts** 12 | 13 | ```ts, ignore 14 | import "./imported.ts"; 15 | 16 | const handler = (e: Event): void => { 17 | console.log(`got ${e.type} event in event handler (main)`); 18 | }; 19 | 20 | globalThis.addEventListener("load", handler); 21 | 22 | globalThis.addEventListener("unload", handler); 23 | 24 | globalThis.onload = (e: Event): void => { 25 | console.log(`got ${e.type} event in onload function (main)`); 26 | }; 27 | 28 | globalThis.onunload = (e: Event): void => { 29 | console.log(`got ${e.type} event in onunload function (main)`); 30 | }; 31 | 32 | console.log("log from main script"); 33 | ``` 34 | 35 | **imported.ts** 36 | 37 | ```ts 38 | const handler = (e: Event): void => { 39 | console.log(`got ${e.type} event in event handler (imported)`); 40 | }; 41 | 42 | globalThis.addEventListener("load", handler); 43 | globalThis.addEventListener("unload", handler); 44 | 45 | globalThis.onload = (e: Event): void => { 46 | console.log(`got ${e.type} event in onload function (imported)`); 47 | }; 48 | 49 | globalThis.onunload = (e: Event): void => { 50 | console.log(`got ${e.type} event in onunload function (imported)`); 51 | }; 52 | 53 | console.log("log from imported script"); 54 | ``` 55 | 56 | A couple notes on this example: 57 | 58 | - `addEventListener` and `onload`/`onunload` are prefixed with `globalThis`, but 59 | you could also use `self` or no prefix at all. 60 | [It is not recommended to use `window` as a prefix](https://lint.deno.land/#no-window-prefix). 61 | - You can use `addEventListener` and/or `onload`/`onunload` to define handlers 62 | for events. There is a major difference between them, let's run the example: 63 | 64 | ```shell 65 | $ deno run main.ts 66 | log from imported script 67 | log from main script 68 | got load event in event handler (imported) 69 | got load event in event handler (main) 70 | got load event in onload function (main) 71 | got unload event in event handler (imported) 72 | got unload event in event handler (main) 73 | got unload event in onunload function (main) 74 | ``` 75 | 76 | All listeners added using `addEventListener` were run, but `onload` and 77 | `onunload` defined in `main.ts` overrode handlers defined in `imported.ts`. 78 | 79 | In other words, you can use `addEventListener` to register multiple `"load"` or 80 | `"unload"` event handlers, but only the last loaded `onload` or `onunload` event 81 | handlers will be executed. It is preferable to use `addEventListener` when 82 | possible for this reason. 83 | -------------------------------------------------------------------------------- /examples/os_signals.md: -------------------------------------------------------------------------------- 1 | # Handle OS Signals 2 | 3 | > ⚠️ Handling OS signals is currently not available on Windows. 4 | 5 | ## Concepts 6 | 7 | - [Deno.addSignalListener()](https://doc.deno.land/deno/stable/~/Deno.addSignalListener) 8 | can be used to capture and monitor OS signals. 9 | - [Deno.removeSignalListener()](https://doc.deno.land/deno/stable/~/Deno.removeSignalListener) 10 | can be used to 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/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](../getting_started/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). The 58 | standard library's [streams module](https://deno.land/std@$STD_VERSION/streams/) 59 | can be used to convert a Deno file into a writable or readable stream. 60 | 61 | **Command:** `deno run --allow-read --allow-write --allow-net fetch_file.ts` 62 | 63 | ```ts 64 | /** 65 | * Receiving a file 66 | */ 67 | import { writableStreamFromWriter } from "https://deno.land/std@$STD_VERSION/streams/mod.ts"; 68 | 69 | const fileResponse = await fetch("https://deno.land/logo.svg"); 70 | 71 | if (fileResponse.body) { 72 | const file = await Deno.open("./logo.svg", { write: true, create: true }); 73 | const writableStream = writableStreamFromWriter(file); 74 | await fileResponse.body.pipeTo(writableStream); 75 | } 76 | 77 | /** 78 | * Sending a file 79 | */ 80 | import { readableStreamFromReader } from "https://deno.land/std@$STD_VERSION/streams/mod.ts"; 81 | 82 | const file = await Deno.open("./logo.svg", { read: true }); 83 | const readableStream = readableStreamFromReader(file); 84 | 85 | await fetch("https://example.com/", { 86 | method: "POST", 87 | body: readableStream, 88 | }); 89 | ``` 90 | -------------------------------------------------------------------------------- /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/ 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/ or 12 | https://deno.land/std/version.ts. The standard library is released each time 13 | 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 | 33 | ## Troubleshooting 34 | 35 | Some of the modules provided in standard library use unstable Deno APIs. 36 | 37 | Trying to run such modules without `--unstable` CLI flag ends up with a lot of 38 | TypeScript errors suggesting that some APIs in the `Deno` namespace do not 39 | exist: 40 | 41 | ```typescript 42 | // main.ts 43 | import { copy } from "https://deno.land/std@$STD_VERSION/fs/copy.ts"; 44 | 45 | copy("log.txt", "log-old.txt"); 46 | ``` 47 | 48 | ```shell 49 | $ deno run --allow-read --allow-write main.ts 50 | Compile file:///dev/deno/main.ts 51 | Download https://deno.land/std@$STD_VERSION/fs/copy.ts 52 | Download https://deno.land/std@$STD_VERSION/fs/ensure_dir.ts 53 | Download https://deno.land/std@$STD_VERSION/fs/_util.ts 54 | error: TS2339 [ERROR]: Property 'utime' does not exist on type 'typeof Deno'. 'Deno.utime' is an unstable API. Did you forget to run with the '--unstable' flag? 55 | await Deno.utime(dest, statInfo.atime, statInfo.mtime); 56 | ~~~~~ 57 | at https://deno.land/std@$STD_VERSION/fs/copy.ts:92:16 58 | 59 | TS2339 [ERROR]: Property 'utimeSync' does not exist on type 'typeof Deno'. 'Deno.utimeSync' is an unstable API. Did you forget to run with the '--unstable' flag? 60 | Deno.utimeSync(dest, statInfo.atime, statInfo.mtime); 61 | ~~~~~~~~~ 62 | at https://deno.land/std@$STD_VERSION/fs/copy.ts:103:10 63 | ``` 64 | 65 | Solution to that problem requires adding `--unstable` flag: 66 | 67 | ```shell 68 | deno run --allow-read --allow-write --unstable main.ts 69 | ``` 70 | 71 | To make sure that API producing error is unstable check 72 | [`lib.deno.unstable.d.ts`](https://github.com/denoland/deno/blob/$CLI_VERSION/cli/dts/lib.deno.unstable.d.ts) 73 | declaration. 74 | 75 | This problem should be fixed in the near future. Feel free to omit the flag if 76 | the particular modules you depend on compile successfully without it. 77 | -------------------------------------------------------------------------------- /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/testing/asserts.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 | -------------------------------------------------------------------------------- /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 runtime with secure defaults and 5 | a great developer experience. 6 | 7 | It's built on V8, Rust, and Tokio. 8 | 9 | ## Feature highlights 10 | 11 | - Web compatible where possible, for example through usage of ES modules, and 12 | support for `fetch`. 13 | - Secure by default. No file, network, or environment access (unless explicitly 14 | enabled). 15 | - Supports TypeScript out of the box. 16 | - Ships a single executable (`deno`). 17 | - Has built-in utilities like a code formatter (`deno fmt`), a linter 18 | (`deno lint`), and a test runner (`deno test`). 19 | - Has 20 | [a set of reviewed (audited) standard 21 | library](https://github.com/denoland/deno_std) that are guaranteed to work 22 | with Deno. 23 | - Can bundle scripts into a single JavaScript file. 24 | 25 | ## Philosophy 26 | 27 | Deno aims to be a productive and secure scripting environment for the modern 28 | programmer. 29 | 30 | Deno will always be distributed as a single executable. Given a URL to a Deno 31 | program, it is runnable with nothing more than 32 | [the ~25 megabyte zipped executable](https://github.com/denoland/deno/releases). 33 | Deno explicitly takes on the role of both runtime and package manager. It uses a 34 | standard browser-compatible protocol for loading modules: URLs. 35 | 36 | Among other things, Deno is a great replacement for utility scripts that may 37 | have been historically written with Bash or Python. 38 | 39 | ## Goals 40 | 41 | - Ship as just a single executable (`deno`). 42 | - Provide secure defaults. 43 | - Unless specifically allowed, scripts can't access files, the environment, or 44 | the network. 45 | - Be browser-compatible. 46 | - The subset of Deno programs which are written completely in JavaScript and 47 | do not use the global `Deno` namespace (or feature test for it), ought to 48 | also be able to be run in a modern web browser without change. 49 | - Provide built-in tooling to improve developer experience. 50 | - E.g. unit testing, code formatting, and linting. 51 | - Keep V8 concepts out of user land. 52 | - Serve HTTP efficiently. 53 | 54 | ## Comparison to Node.js 55 | 56 | - Deno does not use `npm`. 57 | - It uses modules referenced as URLs or file paths. 58 | - Deno does not use `package.json` in its module resolution algorithm. 59 | - All async actions in Deno return a promise. Thus Deno provides different APIs 60 | than Node. 61 | - Deno requires explicit permissions for file, network, and environment access. 62 | - Deno always dies on uncaught errors. 63 | - Deno uses "ES Modules" and does not support `require()`. Third party modules 64 | are imported via URLs: 65 | 66 | ```javascript 67 | import * as log from "https://deno.land/std@$STD_VERSION/log/mod.ts"; 68 | ``` 69 | 70 | ## Other key behaviors 71 | 72 | - Fetch and cache remote code upon first execution, and never update it until 73 | the code is run with the `--reload` flag. (So, this will still work on an 74 | airplane.) 75 | - Modules/files loaded from remote URLs are intended to be immutable and 76 | cacheable. 77 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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@0.132.0/testing/asserts.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 | -------------------------------------------------------------------------------- /linking_to_external_code/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. Use the `--lock=lock.json` to enable and specify lock file checking. To 18 | update or create a lock use `--lock=lock.json --lock-write`. The 19 | `--lock=lock.json` tells Deno what the lock file to use is, while the 20 | `--lock-write` is used to output dependency hashes to the lock file 21 | (`--lock-write` must be used in conjunction with `--lock`). 22 | 23 | A `lock.json` might look like this, storing a hash of the file against the 24 | dependency: 25 | 26 | ```json 27 | { 28 | "https://deno.land/std@$STD_VERSION/textproto/mod.ts": "3118d7a42c03c242c5a49c2ad91c8396110e14acca1324e7aaefd31a999b71a4", 29 | "https://deno.land/std@$STD_VERSION/io/util.ts": "ae133d310a0fdcf298cea7bc09a599c49acb616d34e148e263bcb02976f80dee", 30 | "https://deno.land/std@$STD_VERSION/async/delay.ts": "35957d585a6e3dd87706858fb1d6b551cb278271b03f52c5a2cb70e65e00c26a", 31 | ... 32 | } 33 | ``` 34 | 35 | A typical workflow will look like this: 36 | 37 | **src/deps.ts** 38 | 39 | ```ts, ignore 40 | // Add a new dependency to "src/deps.ts", used somewhere else. 41 | export { xyz } from "https://unpkg.com/xyz-lib@v0.9.0/lib.ts"; 42 | ``` 43 | 44 | Then: 45 | 46 | ```shell 47 | # Create/update the lock file "lock.json". 48 | deno cache --lock=lock.json --lock-write src/deps.ts 49 | 50 | # Include it when committing to source control. 51 | git add -u lock.json 52 | git commit -m "feat: Add support for xyz using xyz-lib" 53 | git push 54 | ``` 55 | 56 | Collaborator on another machine -- in a freshly cloned project tree: 57 | 58 | ```shell 59 | # Download the project's dependencies into the machine's cache, integrity 60 | # checking each resource. 61 | deno cache --reload --lock=lock.json src/deps.ts 62 | 63 | # Done! You can proceed safely. 64 | deno test --allow-read src 65 | ``` 66 | 67 | ### Runtime verification 68 | 69 | Like caching above, you can also use the `--lock=lock.json` option during use of 70 | the `deno run` sub command, validating the integrity of any locked modules 71 | during the run. Remember that this only validates against dependencies 72 | previously added to the `lock.json` file. New dependencies will be cached but 73 | not validated. 74 | 75 | You can take this a step further as well by using the `--cached-only` flag to 76 | require that remote dependencies are already cached. 77 | 78 | ```shell 79 | deno run --lock=lock.json --cached-only mod.ts 80 | ``` 81 | 82 | This will fail if there are any dependencies in the dependency tree for mod.ts 83 | which are not yet cached. 84 | 85 | 86 | -------------------------------------------------------------------------------- /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@0.132.0/testing/asserts.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 | -------------------------------------------------------------------------------- /examples/read_write_files.md: -------------------------------------------------------------------------------- 1 | # Read and write files 2 | 3 | ## Concepts 4 | 5 | - Deno's runtime API provides the 6 | [Deno.readTextFile](https://doc.deno.land/deno/stable/~/Deno.readTextFile) and 7 | [Deno.writeTextFile](https://doc.deno.land/deno/stable/~/Deno.writeTextFile) 8 | asynchronous functions for reading and writing entire text files. 9 | - Like many of Deno's APIs, synchronous alternatives are also available. See 10 | [Deno.readTextFileSync](https://doc.deno.land/deno/stable/~/Deno.readTextFileSync) 11 | and 12 | [Deno.writeTextFileSync](https://doc.deno.land/deno/stable/~/Deno.writeTextFileSync). 13 | - Use `--allow-read` and `--allow-write` permissions to gain access to the file 14 | system. 15 | 16 | ## Overview 17 | 18 | Interacting with the filesystem to read and write files is a common requirement. 19 | Deno provides a number of ways to do this via the 20 | [standard library](https://deno.land/std) and the 21 | [Deno runtime API](https://doc.deno.land/deno/stable). 22 | 23 | As highlighted in the [Fetch Data example](./fetch_data) Deno restricts access 24 | to Input / Output by default for security reasons. Therefore when interacting 25 | with the filesystem the `--allow-read` and `--allow-write` flags must be used 26 | with the `deno run` command. 27 | 28 | ## Reading a text file 29 | 30 | The Deno runtime API makes it possible to read text files via the 31 | `Deno.readTextFile()` method, it just requires a path string or URL object. The 32 | method returns a promise which provides access to the file's text data. 33 | 34 | **Command:** `deno run --allow-read read.ts` 35 | 36 | ```typescript 37 | /** 38 | * read.ts 39 | */ 40 | const text = await Deno.readTextFile("./people.json"); 41 | console.log(text); 42 | 43 | /** 44 | * Output: 45 | * 46 | * [ 47 | * {"id": 1, "name": "John", "age": 23}, 48 | * {"id": 2, "name": "Sandra", "age": 51}, 49 | * {"id": 5, "name": "Devika", "age": 11} 50 | * ] 51 | */ 52 | ``` 53 | 54 | ## Writing a text file 55 | 56 | The Deno runtime API allows developers to write text to files via the 57 | `Deno.writeTextFile()` method. It just requires a file path and text string. The 58 | method returns a promise which resolves when the file was successfully written. 59 | 60 | To run the command the `--allow-write` flag must be supplied to the `deno run` 61 | command. 62 | 63 | **Command:** `deno run --allow-write write.ts` 64 | 65 | ```typescript 66 | /** 67 | * write.ts 68 | */ 69 | await Deno.writeTextFile("./hello.txt", "Hello World!"); 70 | console.log("File written to ./hello.txt"); 71 | 72 | /** 73 | * Output: File written to ./hello.txt 74 | */ 75 | ``` 76 | 77 | By combining `Deno.writeTextFile` and `JSON.stringify` you can easily write 78 | serialized JSON objects to a file. This example uses synchronous 79 | `Deno.writeTextFileSync`, but this can also be done asynchronously using 80 | `await Deno.writeTextFile`. 81 | 82 | To execute the code the `deno run` command needs the write flag. 83 | 84 | **Command:** `deno run --allow-write write.ts` 85 | 86 | ```typescript 87 | /** 88 | * write.ts 89 | */ 90 | function writeJson(path: string, data: object): string { 91 | try { 92 | Deno.writeTextFileSync(path, JSON.stringify(data)); 93 | 94 | return "Written to " + path; 95 | } catch (e) { 96 | return e.message; 97 | } 98 | } 99 | 100 | console.log(writeJson("./data.json", { hello: "World" })); 101 | 102 | /** 103 | * Output: Written to ./data.json 104 | */ 105 | ``` 106 | -------------------------------------------------------------------------------- /linking_to_external_code/private.md: -------------------------------------------------------------------------------- 1 | ## Private modules and repositories 2 | 3 | There maybe 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 is 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 a _n_ 16 | number of tokens deliminated by a semi-colon (`;`) where each token is either: 17 | 18 | - a bearer token in the format of `{token}@{hostname[:port]}` 19 | 20 | - basic auth data in the format of `{username}:{password}@{hostname[:port]}` 21 | 22 | For example a single token for 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 be able to access private repositories on GitHub, you would need to issue 50 | yourself a _personal access token_. You do this by logging into GitHub and going 51 | under _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 | -------------------------------------------------------------------------------- /node.md: -------------------------------------------------------------------------------- 1 | # Interoperating with Node and NPM 2 | 3 | While Deno is pretty powerful itself, many people will want to leverage code and 4 | libraries that are built for [Node](https://nodejs.org/), in particular the 5 | large set of packages available on the [NPM](https://npmjs.com/) registry. In 6 | this chapter, we will explore how. 7 | 8 | > ⚠️ Starting with v1.15 Deno provides a compatibility mode, that allows to 9 | > emulate Node environment and consume code authored for Node directly. See 10 | > [Node compatibility mode](./node/compatibility_mode.md) chapter for details. 11 | 12 | The good news is that in many cases, it _just works_. 13 | 14 | There are some foundational things to understand about differences between Node 15 | and Deno that can help in understanding what challenges might be faced: 16 | 17 | - Current Node supports both CommonJS and ES Modules, while Deno only supports 18 | ES Modules. The addition of stabilized ES Modules in Node is relatively recent 19 | and most code written for Node is in the CommonJS format. 20 | - Node has quite a few built-in modules that can be imported and they are a 21 | fairly expansive set of APIs. On the other hand, Deno focuses on implementing 22 | web standards, and where functionality goes beyond the browser, we locate APIs 23 | in a single global `Deno` variable/namespace. Lots of code written for Node 24 | expects/depends upon these built-in APIs to be available. 25 | - Node has a non-standards based module resolution algorithm, where you can 26 | import bare-specifiers (e.g. `react` or `lodash`) and Node will look in your 27 | local and global `node_modules` for a path, introspect the `package.json` and 28 | try to see if there is a module named the right way. Deno resolves modules the 29 | same way a browser does. For local files, Deno expects a full module name, 30 | including the extension. When dealing with remote imports, Deno expects the 31 | web server to do any "resolving" and provide back the media type of the code 32 | (see the 33 | [Determining the type of file](./typescript/overview.md#determining-the-type-of-file) 34 | for more information). 35 | - Node effectively doesn't work without a `package.json` file. Deno doesn't 36 | require an external meta-data file to function or resolve modules. 37 | - Node doesn't support remote HTTP imports. It expects all 3rd party code to be 38 | installed locally on your machine using a package manager like `npm` into the 39 | local or global `node_modules` folder. Deno supports remote HTTP imports (as 40 | well as `data` and `blob` URLs) and will go ahead and fetch the remote code 41 | and cache it locally, similar to the way a browser works. 42 | 43 | In order to help mitigate these differences, we will further explore in this 44 | chapter: 45 | 46 | - Using the [`std/node`](./node/std_node.md) modules of the Deno standard 47 | library to "polyfill" the built-in modules of Node 48 | - Using [CDNs](./node/cdns.md) to access the vast majority of npm packages in 49 | ways that work under Deno. 50 | - How [import maps](./node/import_maps.md) can be used to provide "bare 51 | specifier" imports like Node under Deno, without needing to use a package 52 | manager to install packages locally. 53 | - And finally, a general section of [frequently asked questions](./node/faqs.md) 54 | 55 | That being said, some differences cannot be overcome: 56 | 57 | - Node has a plugin system that is incompatible with Deno, and Deno will never 58 | support Node plugins. If the Node code you want to use requires a "native" 59 | Node plugin, it won't work under Deno. 60 | - Node has some built-in modules (e.g. like `vm`) that are effectively 61 | incompatible with the scope of Deno and therefore there aren't easy ways to 62 | provide a _polyfill_ of the functionality in Deno. 63 | -------------------------------------------------------------------------------- /examples/import_export.md: -------------------------------------------------------------------------------- 1 | # Import and export modules 2 | 3 | ## Concepts 4 | 5 | - [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) 6 | allows you to include and use modules held elsewhere, on your local file 7 | system or remotely. 8 | - Imports are URLs or file system paths. 9 | - [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) 10 | allows you to specify which parts of your module are accessible to users who 11 | import your module. 12 | 13 | ## Overview 14 | 15 | Deno by default standardizes the way modules are imported in both JavaScript and 16 | TypeScript using the ECMAScript 6 `import/export` standard. 17 | 18 | It adopts browser-like module resolution, meaning that file names must be 19 | specified in full. You may not omit the file extension and there is no special 20 | handling of `index.js`. 21 | 22 | ```js, ignore 23 | import { add, multiply } from "./arithmetic.ts"; 24 | ``` 25 | 26 | Dependencies are also imported directly, there is no package management 27 | overhead. Local modules are imported in exactly the same way as remote modules. 28 | As the examples show below, the same functionality can be produced in the same 29 | way with local or remote modules. 30 | 31 | ## Local Import 32 | 33 | In this example the `add` and `multiply` functions are imported from a local 34 | `arithmetic.ts` module. 35 | 36 | **Command:** `deno run local.ts` 37 | 38 | ```ts, ignore 39 | /** 40 | * local.ts 41 | */ 42 | import { add, multiply } from "./arithmetic.ts"; 43 | 44 | function totalCost(outbound: number, inbound: number, tax: number): number { 45 | return multiply(add(outbound, inbound), tax); 46 | } 47 | 48 | console.log(totalCost(19, 31, 1.2)); 49 | console.log(totalCost(45, 27, 1.15)); 50 | 51 | /** 52 | * Output 53 | * 54 | * 60 55 | * 82.8 56 | */ 57 | ``` 58 | 59 | ## Remote Import 60 | 61 | In the local import example above an `add` and `multiply` method are imported 62 | from a locally stored arithmetic module. The same functionality can be created 63 | by importing `add` and `multiply` methods from a remote module too. 64 | 65 | In this case the Ramda module is referenced, including the version number. Also 66 | note a JavaScript module is imported directly into a TypeScript module, Deno has 67 | no problem handling this. 68 | 69 | **Command:** `deno run ./remote.ts` 70 | 71 | ```ts 72 | /** 73 | * remote.ts 74 | */ 75 | import { 76 | add, 77 | multiply, 78 | } from "https://x.nest.land/ramda@0.27.0/source/index.js"; 79 | 80 | function totalCost(outbound: number, inbound: number, tax: number): number { 81 | return multiply(add(outbound, inbound), tax); 82 | } 83 | 84 | console.log(totalCost(19, 31, 1.2)); 85 | console.log(totalCost(45, 27, 1.15)); 86 | 87 | /** 88 | * Output 89 | * 90 | * 60 91 | * 82.8 92 | */ 93 | ``` 94 | 95 | ## Export 96 | 97 | In the local import example above the `add` and `multiply` functions are 98 | imported from a locally stored arithmetic module. To make this possible the 99 | functions stored in the arithmetic module must be exported. 100 | 101 | To do this just add the keyword `export` to the beginning of the function 102 | signature as is shown below. 103 | 104 | ```ts 105 | /** 106 | * arithmetic.ts 107 | */ 108 | export function add(a: number, b: number): number { 109 | return a + b; 110 | } 111 | 112 | export function multiply(a: number, b: number): number { 113 | return a * b; 114 | } 115 | ``` 116 | 117 | All functions, classes, constants and variables which need to be accessible 118 | inside external modules must be exported. Either by prepending them with the 119 | `export` keyword or including them in an export statement at the bottom of the 120 | file. 121 | -------------------------------------------------------------------------------- /contributing/building_from_source.md: -------------------------------------------------------------------------------- 1 | ## Building `deno` from source 2 | 3 | Below are instructions on how to build Deno from source. If you just want to use 4 | Deno you can download a prebuilt executable (more information in the 5 | [`Getting Started`](../getting_started/installation.md#download-and-install) 6 | chapter). 7 | 8 | ### Cloning the Repository 9 | 10 | Clone on Linux or Mac: 11 | 12 | ```shell 13 | git clone --recurse-submodules https://github.com/denoland/deno.git 14 | ``` 15 | 16 | Extra steps for Windows users: 17 | 18 | 1. [Enable "Developer Mode"](https://www.google.com/search?q=windows+enable+developer+mode) 19 | (otherwise symlinks would require administrator privileges). 20 | 2. Make sure you are using git version 2.19.2.windows.1 or newer. 21 | 3. Set `core.symlinks=true` before the checkout: 22 | ```shell 23 | git config --global core.symlinks true 24 | git clone --recurse-submodules https://github.com/denoland/deno.git 25 | ``` 26 | 27 | ### Prerequisites 28 | 29 | > Deno requires the progressively latest stable release of Rust. Deno does not 30 | > support the Rust Nightly Releases. 31 | 32 | [Update or Install Rust](https://www.rust-lang.org/tools/install). Check that 33 | Rust installed/updated correctly: 34 | 35 | ``` 36 | rustc -V 37 | cargo -V 38 | ``` 39 | 40 | For Apple aarch64 users `lld` must be installed. 41 | 42 | ``` 43 | brew install llvm 44 | # Add /opt/homebrew/opt/llvm/bin/ to $PATH 45 | ``` 46 | 47 | ### Building Deno 48 | 49 | The easiest way to build Deno is by using a precompiled version of V8: 50 | 51 | ``` 52 | cargo build -vv 53 | ``` 54 | 55 | However if you want to build Deno and V8 from source code: 56 | 57 | ``` 58 | V8_FROM_SOURCE=1 cargo build -vv 59 | ``` 60 | 61 | When building V8 from source, there are more dependencies: 62 | 63 | [Python 3](https://www.python.org/downloads) for running WPT tests. Ensure that 64 | a suffix-less `python`/`python.exe` exists in your `PATH` and it refers to 65 | Python 3. 66 | 67 | For Linux users glib-2.0 development files must also be installed. (On Ubuntu, 68 | run `apt install libglib2.0-dev`.) 69 | 70 | Mac users must have Command Line Tools installed. 71 | ([XCode](https://developer.apple.com/xcode/) already includes CLT. Run 72 | `xcode-select --install` to install it without XCode.) 73 | 74 | For Windows users: 75 | 76 | 1. Get [VS Community 2019](https://www.visualstudio.com/downloads/) with 77 | "Desktop development with C++" toolkit and make sure to select the following 78 | required tools listed below along with all C++ tools. 79 | 80 | - Visual C++ tools for CMake 81 | - Windows 10 SDK (10.0.17763.0) 82 | - Testing tools core features - Build Tools 83 | - Visual C++ ATL for x86 and x64 84 | - Visual C++ MFC for x86 and x64 85 | - C++/CLI support 86 | - VC++ 2015.3 v14.00 (v140) toolset for desktop 87 | 88 | 2. Enable "Debugging Tools for Windows". Go to "Control Panel" → "Programs" → 89 | "Programs and Features" → Select "Windows Software Development Kit - Windows 90 | 10" → "Change" → "Change" → Check "Debugging Tools For Windows" → "Change" → 91 | "Finish". Or use: 92 | [Debugging Tools for Windows](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/) 93 | (Notice: it will download the files, you should install 94 | `X64 Debuggers And Tools-x64_en-us.msi` file manually.) 95 | 96 | See [rusty_v8's README](https://github.com/denoland/rusty_v8) for more details 97 | about the V8 build. 98 | 99 | ### Building 100 | 101 | Build with Cargo: 102 | 103 | ```shell 104 | # Build: 105 | cargo build -vv 106 | 107 | # Build errors? Ensure you have latest main and try building again, or if that doesn't work try: 108 | cargo clean && cargo build -vv 109 | 110 | # Run: 111 | ./target/debug/deno run cli/tests/testdata/002_hello.ts 112 | ``` 113 | -------------------------------------------------------------------------------- /tools/dependency_inspector.md: -------------------------------------------------------------------------------- 1 | ## Dependency Inspector 2 | 3 | `deno info [URL]` will inspect an ES module and all of its dependencies. 4 | 5 | ```shell 6 | deno info https://deno.land/std@0.67.0/http/file_server.ts 7 | Download https://deno.land/std@0.67.0/http/file_server.ts 8 | ... 9 | local: /home/deno/.cache/deno/deps/https/deno.land/f57792e36f2dbf28b14a75e2372a479c6392780d4712d76698d5031f943c0020 10 | type: TypeScript 11 | emit: /home/deno/.cache/deno/gen/https/deno.land/f57792e36f2dbf28b14a75e2372a479c6392780d4712d76698d5031f943c0020.js 12 | dependencies: 23 unique (total 139.89KB) 13 | https://deno.land/std@0.67.0/http/file_server.ts (10.49KB) 14 | ├─┬ https://deno.land/std@0.67.0/path/mod.ts (717B) 15 | │ ├── https://deno.land/std@0.67.0/path/_constants.ts (2.35KB) 16 | │ ├─┬ https://deno.land/std@0.67.0/path/win32.ts (27.36KB) 17 | │ │ ├── https://deno.land/std@0.67.0/path/_interface.ts (657B) 18 | │ │ ├── https://deno.land/std@0.67.0/path/_constants.ts * 19 | │ │ ├─┬ https://deno.land/std@0.67.0/path/_util.ts (3.3KB) 20 | │ │ │ ├── https://deno.land/std@0.67.0/path/_interface.ts * 21 | │ │ │ └── https://deno.land/std@0.67.0/path/_constants.ts * 22 | │ │ └── https://deno.land/std@0.67.0/_util/assert.ts (405B) 23 | │ ├─┬ https://deno.land/std@0.67.0/path/posix.ts (12.67KB) 24 | │ │ ├── https://deno.land/std@0.67.0/path/_interface.ts * 25 | │ │ ├── https://deno.land/std@0.67.0/path/_constants.ts * 26 | │ │ └── https://deno.land/std@0.67.0/path/_util.ts * 27 | │ ├─┬ https://deno.land/std@0.67.0/path/common.ts (1.14KB) 28 | │ │ └─┬ https://deno.land/std@0.67.0/path/separator.ts (264B) 29 | │ │ └── https://deno.land/std@0.67.0/path/_constants.ts * 30 | │ ├── https://deno.land/std@0.67.0/path/separator.ts * 31 | │ ├── https://deno.land/std@0.67.0/path/_interface.ts * 32 | │ └─┬ https://deno.land/std@0.67.0/path/glob.ts (8.12KB) 33 | │ ├── https://deno.land/std@0.67.0/path/_constants.ts * 34 | │ ├── https://deno.land/std@0.67.0/path/mod.ts * 35 | │ └── https://deno.land/std@0.67.0/path/separator.ts * 36 | ├─┬ https://deno.land/std@0.67.0/http/server.ts (10.23KB) 37 | │ ├── https://deno.land/std@0.67.0/encoding/utf8.ts (433B) 38 | │ ├─┬ https://deno.land/std@0.67.0/io/bufio.ts (21.15KB) 39 | │ │ ├── https://deno.land/std@0.67.0/bytes/mod.ts (4.34KB) 40 | │ │ └── https://deno.land/std@0.67.0/_util/assert.ts * 41 | │ ├── https://deno.land/std@0.67.0/_util/assert.ts * 42 | │ ├─┬ https://deno.land/std@0.67.0/async/mod.ts (202B) 43 | │ │ ├── https://deno.land/std@0.67.0/async/deferred.ts (1.03KB) 44 | │ │ ├── https://deno.land/std@0.67.0/async/delay.ts (279B) 45 | │ │ ├─┬ https://deno.land/std@0.67.0/async/mux_async_iterator.ts (1.98KB) 46 | │ │ │ └── https://deno.land/std@0.67.0/async/deferred.ts * 47 | │ │ └── https://deno.land/std@0.67.0/async/pool.ts (1.58KB) 48 | │ └─┬ https://deno.land/std@0.67.0/http/_io.ts (11.25KB) 49 | │ ├── https://deno.land/std@0.67.0/io/bufio.ts * 50 | │ ├─┬ https://deno.land/std@0.67.0/textproto/mod.ts (4.52KB) 51 | │ │ ├── https://deno.land/std@0.67.0/io/bufio.ts * 52 | │ │ ├── https://deno.land/std@0.67.0/bytes/mod.ts * 53 | │ │ └── https://deno.land/std@0.67.0/encoding/utf8.ts * 54 | │ ├── https://deno.land/std@0.67.0/_util/assert.ts * 55 | │ ├── https://deno.land/std@0.67.0/encoding/utf8.ts * 56 | │ ├── https://deno.land/std@0.67.0/http/server.ts * 57 | │ └── https://deno.land/std@0.67.0/http/http_status.ts (5.93KB) 58 | ├─┬ https://deno.land/std@0.67.0/flags/mod.ts (9.54KB) 59 | │ └── https://deno.land/std@0.67.0/_util/assert.ts * 60 | └── https://deno.land/std@0.67.0/_util/assert.ts * 61 | ``` 62 | 63 | Dependency inspector works with any local or remote ES modules. 64 | 65 | ## Cache location 66 | 67 | `deno info` can be used to display information about cache location: 68 | 69 | ```shell 70 | deno info 71 | DENO_DIR location: "/Users/deno/Library/Caches/deno" 72 | Remote modules cache: "/Users/deno/Library/Caches/deno/deps" 73 | TypeScript compiler cache: "/Users/deno/Library/Caches/deno/gen" 74 | ``` 75 | -------------------------------------------------------------------------------- /linking_to_external_code.md: -------------------------------------------------------------------------------- 1 | # Linking to third party code 2 | 3 | In the [Getting Started](./getting_started.md) section, we saw Deno could 4 | execute scripts from URLs. Like browser JavaScript, Deno can import libraries 5 | directly from URLs. This example uses a URL to import an assertion library: 6 | 7 | **test.ts** 8 | 9 | ```ts 10 | import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts"; 11 | 12 | assertEquals("hello", "hello"); 13 | assertEquals("world", "world"); 14 | 15 | console.log("Asserted! ✓"); 16 | ``` 17 | 18 | Try running this: 19 | 20 | ```shell 21 | $ deno run test.ts 22 | Compile file:///mnt/f9/Projects/github.com/denoland/deno/docs/test.ts 23 | Download https://deno.land/std@$STD_VERSION/testing/asserts.ts 24 | Download https://deno.land/std@$STD_VERSION/fmt/colors.ts 25 | Download https://deno.land/std@$STD_VERSION/testing/diff.ts 26 | Asserted! ✓ 27 | ``` 28 | 29 | Note that we did not have to provide the `--allow-net` flag for this program, 30 | and yet it accessed the network. The runtime has special access to download 31 | imports and cache them to disk. 32 | 33 | Deno caches remote imports in a special directory specified by the `DENO_DIR` 34 | environment variable. It defaults to the system's cache directory if `DENO_DIR` 35 | is not specified. The next time you run the program, no downloads will be made. 36 | If the program hasn't changed, it won't be recompiled either. The default 37 | directory is: 38 | 39 | - On Linux/Redox: `$XDG_CACHE_HOME/deno` or `$HOME/.cache/deno` 40 | - On Windows: `%LOCALAPPDATA%/deno` (`%LOCALAPPDATA%` = `FOLDERID_LocalAppData`) 41 | - On macOS: `$HOME/Library/Caches/deno` 42 | - If something fails, it falls back to `$HOME/.deno` 43 | 44 | ## FAQ 45 | 46 | ### How do I import a specific version of a module? 47 | 48 | Specify the version in the URL. For example, this URL fully specifies the code 49 | being run: `https://unpkg.com/liltest@0.0.5/dist/liltest.js`. 50 | 51 | ### It seems unwieldy to import URLs everywhere. 52 | 53 | > What if one of the URLs links to a subtly different version of a library? 54 | 55 | > Isn't it error prone to maintain URLs everywhere in a large project? 56 | 57 | The solution is to import and re-export your external libraries in a central 58 | `deps.ts` file (which serves the same purpose as Node's `package.json` file). 59 | For example, let's say you were using the above assertion library across a large 60 | project. Rather than importing 61 | `"https://deno.land/std@$STD_VERSION/testing/asserts.ts"` everywhere, you could 62 | create a `deps.ts` file that exports the third-party code: 63 | 64 | **deps.ts** 65 | 66 | ```ts 67 | export { 68 | assert, 69 | assertEquals, 70 | assertStringIncludes, 71 | } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts"; 72 | ``` 73 | 74 | And throughout the same project, you can import from the `deps.ts` and avoid 75 | having many references to the same URL: 76 | 77 | ```ts, ignore 78 | import { assertEquals, runTests, test } from "./deps.ts"; 79 | ``` 80 | 81 | This design circumvents a plethora of complexity spawned by package management 82 | software, centralized code repositories, and superfluous file formats. 83 | 84 | ### How can I trust a URL that may change? 85 | 86 | By using a lock file (with the `--lock` command line flag), you can ensure that 87 | the code pulled from a URL is the same as it was during initial development. You 88 | can learn more about this 89 | [here](./linking_to_external_code/integrity_checking.md). 90 | 91 | ### But what if the host of the URL goes down? The source won't be available. 92 | 93 | This, like the above, is a problem faced by _any_ remote dependency system. 94 | Relying on external servers is convenient for development but brittle in 95 | production. Production software should always vendor its dependencies. In Node 96 | this is done by checking `node_modules` into source control. In Deno this is 97 | done by using the [`deno vendor`](./tools/vendor.md) subcommand. 98 | -------------------------------------------------------------------------------- /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 pallette 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 pallette. 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) as as test step. While the vscode UI will allow you to do 82 | this, by for example, choosing to run a specific test step, all test steps in 83 | that test will be run (but vscode will not update the results for them). So if 84 | there are other side effects in the test case, they may occur. 85 | -------------------------------------------------------------------------------- /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 shebangs, 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 | # Rebase to retain our modifications 129 | git rebase origin/master 130 | git push denoland 131 | ``` 132 | 133 | All contributors will need to rerun `./tools/wpt.ts setup` after this. 134 | -------------------------------------------------------------------------------- /examples/file_server.md: -------------------------------------------------------------------------------- 1 | # File server 2 | 3 | ## Concepts 4 | 5 | - Use [Deno.open](https://doc.deno.land/deno/stable/~/Deno.open) to read a 6 | file's content in chunks. 7 | - Use the Deno standard library 8 | [streams module](https://deno.land/std@$STD_VERSION/streams/) to transform a 9 | Deno file into a 10 | [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). 11 | - Use Deno's integrated HTTP server to run your own file server. 12 | 13 | ## Overview 14 | 15 | Sending files over the network is a common requirement. As seen in the 16 | [Fetch Data example](./fetch_data), because files can be of any size, it is 17 | important to use streams in order to prevent having to load entire files into 18 | memory. 19 | 20 | ## Example 21 | 22 | **Command:** `deno run --allow-read --allow-net file_server.ts` 23 | 24 | ```ts 25 | import * as path from "https://deno.land/std@$STD_VERSION/path/mod.ts"; 26 | import { readableStreamFromReader } from "https://deno.land/std@$STD_VERSION/streams/mod.ts"; 27 | 28 | // Start listening on port 8080 of localhost. 29 | const server = Deno.listen({ port: 8080 }); 30 | console.log("File server running on http://localhost:8080/"); 31 | 32 | for await (const conn of server) { 33 | handleHttp(conn); 34 | } 35 | 36 | async function handleHttp(conn: Deno.Conn) { 37 | const httpConn = Deno.serveHttp(conn); 38 | for await (const requestEvent of httpConn) { 39 | // Use the request pathname as filepath 40 | const url = new URL(requestEvent.request.url); 41 | const filepath = decodeURIComponent(url.pathname); 42 | 43 | // Try opening the file 44 | let file; 45 | try { 46 | file = await Deno.open("." + filepath, { read: true }); 47 | const stat = await file.stat(); 48 | 49 | // If File instance is a directory, lookup for an index.html 50 | if (stat.isDirectory) { 51 | file.close(); 52 | const filePath = path.join("./", filepath, "index.html"); 53 | file = await Deno.open(filePath, { read: true }); 54 | } 55 | } catch { 56 | // If the file cannot be opened, return a "404 Not Found" response 57 | const notFoundResponse = new Response("404 Not Found", { status: 404 }); 58 | await requestEvent.respondWith(notFoundResponse); 59 | return; 60 | } 61 | 62 | // Build a readable stream so the file doesn't have to be fully loaded into 63 | // memory while we send it 64 | const readableStream = readableStreamFromReader(file); 65 | 66 | // Build and send the response 67 | const response = new Response(readableStream); 68 | await requestEvent.respondWith(response); 69 | } 70 | } 71 | ``` 72 | 73 | ## Using the `std/http` file server 74 | 75 | The Deno standard library provides you with a 76 | [file server](https://deno.land/std@$STD_VERSION/http/file_server.ts) so that 77 | you don't have to write your own. 78 | 79 | To use it, first install the remote script to your local file system. This will 80 | install the script to the Deno installation root's bin directory, e.g. 81 | `/home/alice/.deno/bin/file_server`. 82 | 83 | ```shell 84 | deno install --allow-net --allow-read https://deno.land/std@$STD_VERSION/http/file_server.ts 85 | ``` 86 | 87 | You can now run the script with the simplified script name. Run it: 88 | 89 | ```shell 90 | $ file_server . 91 | Downloading https://deno.land/std@$STD_VERSION/http/file_server.ts... 92 | [...] 93 | HTTP server listening on http://0.0.0.0:4507/ 94 | ``` 95 | 96 | Now go to [http://0.0.0.0:4507/](http://0.0.0.0:4507/) in your web browser to 97 | see your local directory contents. 98 | 99 | The complete list of options are available via: 100 | 101 | ```shell 102 | file_server --help 103 | ``` 104 | 105 | Example output: 106 | 107 | ``` 108 | Deno File Server 109 | Serves a local directory in HTTP. 110 | INSTALL: 111 | deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts 112 | USAGE: 113 | file_server [path] [options] 114 | OPTIONS: 115 | -h, --help Prints help information 116 | -p, --port Set port 117 | --cors Enable CORS via the "Access-Control-Allow-Origin" header 118 | --host Hostname (default is 0.0.0.0) 119 | -c, --cert TLS certificate file (enables TLS) 120 | -k, --key TLS key file (enables TLS) 121 | --no-dir-listing Disable directory listing 122 | All TLS options are required when one is provided. 123 | ``` 124 | -------------------------------------------------------------------------------- /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](../webassembly.md) might play a part in 22 | 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 provably 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 | -------------------------------------------------------------------------------- /getting_started/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` or 8 | `--inspect-brk` flags. 9 | 10 | The `--inspect` flag allows attaching the debugger at any point in time, while 11 | `--inspect-brk` will wait for the debugger to attach and will pause execution on 12 | the first line of code. 13 | 14 | > ⚠️ If you use `--inspect` flag, the code will start executing immediately. If 15 | > your program is short, you might not have enough time to connect the debugger 16 | > before the program finishes execution. In such cases, try running with 17 | > `--inspect-brk` flag instead, or add a timeout at the end of your code. 18 | 19 | ### Chrome Devtools 20 | 21 | Let's try debugging a program using Chrome Devtools. For this, we'll use 22 | [file_server.ts](https://deno.land/std@$STD_VERSION/http/file_server.ts) from 23 | `std`, a static file server. 24 | 25 | Use the `--inspect-brk` flag to break execution on the first line: 26 | 27 | ```shell 28 | $ deno run --inspect-brk --allow-read --allow-net https://deno.land/std@$STD_VERSION/http/file_server.ts 29 | Debugger listening on ws://127.0.0.1:9229/ws/1e82c406-85a9-44ab-86b6-7341583480b1 30 | Download https://deno.land/std@$STD_VERSION/http/file_server.ts 31 | Compile https://deno.land/std@$STD_VERSION/http/file_server.ts 32 | ... 33 | ``` 34 | 35 | In a Chromium derived browser such as Google Chrome or Microsoft Edge, open 36 | `chrome://inspect` and click `Inspect` next to target: 37 | 38 | ![chrome://inspect](../images/debugger1.jpg) 39 | 40 | It might take a few seconds after opening the DevTools to load all modules. 41 | 42 | ![DevTools opened](../images/debugger2.jpg) 43 | 44 | You might notice that DevTools pauses execution on the first line of 45 | `_constants.ts` instead of `file_server.ts`. This is expected behavior caused by 46 | the way ES modules are evaluated in JavaScript (`_constants.ts` is left-most, 47 | bottom-most dependency of `file_server.ts` so it is evaluated first). 48 | 49 | At this point all source code is available in the DevTools, so let's open up 50 | `file_server.ts` and add a breakpoint there; go to "Sources" pane and expand the 51 | tree: 52 | 53 | ![Open file_server.ts](../images/debugger3.jpg) 54 | 55 | _Looking closely you'll find duplicate entries for each file; one written 56 | regularly and one in italics. The former is compiled source file (so in the case 57 | of `.ts` files it will be emitted JavaScript source), while the latter is a 58 | source map for the file._ 59 | 60 | Next, add a breakpoint in the `listenAndServe` method: 61 | 62 | ![Break in file_server.ts](../images/debugger4.jpg) 63 | 64 | As soon as we've added the breakpoint, DevTools automatically opens up the 65 | source map file, which allows us step through the actual source code that 66 | includes types. 67 | 68 | Now that we have our breakpoints set, we can resume the execution of our script 69 | so that we can inspect an incoming request. Hit the "Resume script execution" 70 | button to do so. You might even need to hit it twice! 71 | 72 | Once our script is running, try send a request and inspect it in Devtools: 73 | 74 | ``` 75 | $ curl http://0.0.0.0:4507/ 76 | ``` 77 | 78 | ![Break in request handling](../images/debugger5.jpg) 79 | 80 | At this point we can introspect the contents of the request and go step-by-step 81 | to debug the code. 82 | 83 | ### VSCode 84 | 85 | Deno can be debugged using VSCode. This is best done with help from the official 86 | `vscode_deno` extension. Documentation for this can be found 87 | [here](../vscode_deno#using-the-debugger). 88 | 89 | ### JetBrains IDEs 90 | 91 | _**Note**: make sure you have 92 | [this Deno plugin](https://plugins.jetbrains.com/plugin/14382-deno) installed 93 | and enabled in Preferences / Settings | Plugins. For more information, see 94 | [this blog post](https://blog.jetbrains.com/webstorm/2020/06/deno-support-in-jetbrains-ides/)._ 95 | 96 | You can debug Deno using your JetBrains IDE by right-clicking the file you want 97 | to debug and selecting the `Debug 'Deno: '` option. 98 | 99 | ![Debug file](../images/jb-ide-debug.png) 100 | 101 | This will create a run/debug configuration with no permission flags set. If you 102 | want to configure them, open your run/debug configuration and add the required 103 | flags to the `Command` field. 104 | 105 | ### Other 106 | 107 | Any client that implements the DevTools protocol should be able to connect to a 108 | Deno process. 109 | -------------------------------------------------------------------------------- /examples/subprocess.md: -------------------------------------------------------------------------------- 1 | # Creating a subprocess 2 | 3 | ## Concepts 4 | 5 | - Deno is capable of spawning a subprocess via 6 | [Deno.run](https://doc.deno.land/deno/stable/~/Deno.run). 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 10 | [stdin](https://doc.deno.land/deno/stable/~/Deno.stdin), 11 | [stdout](https://doc.deno.land/deno/stable/~/Deno.stdout) and 12 | [stderr](https://doc.deno.land/deno/stable/~/Deno.stderr) streams. 13 | - Use a specific shell by providing its path/name and its string input switch, 14 | e.g. `Deno.run({cmd: ["bash", "-c", "ls -la"]});` 15 | 16 | ## Simple example 17 | 18 | This example is the equivalent of running `'echo hello'` from the command line. 19 | 20 | ```ts 21 | /** 22 | * subprocess_simple.ts 23 | */ 24 | 25 | // define command used to create the subprocess 26 | const cmd = ["echo", "hello"]; 27 | 28 | // create subprocess 29 | const p = Deno.run({ cmd }); 30 | 31 | // await its completion 32 | await p.status(); 33 | ``` 34 | 35 | > Note: If using Windows, the command above would need to be written differently 36 | > because `echo` is not an executable binary (rather, it is a built-in shell 37 | > command): 38 | 39 | ```ts 40 | // define command used to create the subprocess 41 | const cmd = ["cmd", "/c", "echo hello"]; 42 | ``` 43 | 44 | Run it: 45 | 46 | ```shell 47 | $ deno run --allow-run ./subprocess_simple.ts 48 | hello 49 | ``` 50 | 51 | ## Security 52 | 53 | The `--allow-run` permission is required for creation of a subprocess. Be aware 54 | that subprocesses are not run in a Deno sandbox and therefore have the same 55 | permissions as if you were to run the command from the command line yourself. 56 | 57 | ## Communicating with subprocesses 58 | 59 | By default when you use `Deno.run()` the subprocess inherits `stdin`, `stdout` 60 | and `stderr` of the parent process. If you want to communicate with started 61 | subprocess you can use `"piped"` option. 62 | 63 | ```ts 64 | /** 65 | * subprocess.ts 66 | */ 67 | const fileNames = Deno.args; 68 | 69 | const p = Deno.run({ 70 | cmd: [ 71 | "deno", 72 | "run", 73 | "--allow-read", 74 | "https://deno.land/std@$STD_VERSION/examples/cat.ts", 75 | ...fileNames, 76 | ], 77 | stdout: "piped", 78 | stderr: "piped", 79 | }); 80 | 81 | const { code } = await p.status(); 82 | 83 | // Reading the outputs closes their pipes 84 | const rawOutput = await p.output(); 85 | const rawError = await p.stderrOutput(); 86 | 87 | if (code === 0) { 88 | await Deno.stdout.write(rawOutput); 89 | } else { 90 | const errorString = new TextDecoder().decode(rawError); 91 | console.log(errorString); 92 | } 93 | 94 | Deno.exit(code); 95 | ``` 96 | 97 | When you run it: 98 | 99 | ```shell 100 | $ deno run --allow-run ./subprocess.ts 101 | [file content] 102 | 103 | $ deno run --allow-run ./subprocess.ts non_existent_file.md 104 | 105 | Uncaught NotFound: No such file or directory (os error 2) 106 | at DenoError (deno/js/errors.ts:22:5) 107 | at maybeError (deno/js/errors.ts:41:12) 108 | at handleAsyncMsgFromRust (deno/js/dispatch.ts:27:17) 109 | ``` 110 | 111 | ## Piping to files 112 | 113 | This example is the equivalent of running `yes &> ./process_output` in bash. 114 | 115 | ```ts 116 | /** 117 | * subprocess_piping_to_file.ts 118 | */ 119 | 120 | import { 121 | readableStreamFromReader, 122 | writableStreamFromWriter, 123 | } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; 124 | import { mergeReadableStreams } from "https://deno.land/std@$STD_VERSION/streams/merge.ts"; 125 | 126 | // create the file to attach the process to 127 | const file = await Deno.open("./process_output.txt", { 128 | read: true, 129 | write: true, 130 | create: true, 131 | }); 132 | const fileWriter = await writableStreamFromWriter(file); 133 | 134 | // start the process 135 | const process = Deno.run({ 136 | cmd: ["yes"], 137 | stdout: "piped", 138 | stderr: "piped", 139 | }); 140 | 141 | // example of combining stdout and stderr while sending to a file 142 | const stdout = readableStreamFromReader(process.stdout); 143 | const stderr = readableStreamFromReader(process.stderr); 144 | const joined = mergeReadableStreams(stdout, stderr); 145 | // returns a promise that resolves when the process is killed/closed 146 | joined.pipeTo(fileWriter).then(() => console.log("pipe join done")); 147 | 148 | // manually stop process "yes" will never end on its own 149 | setTimeout(async () => { 150 | process.kill("SIGINT"); 151 | }, 100); 152 | ``` 153 | 154 | Run it: 155 | 156 | ```shell 157 | $ deno run --allow-run ./subprocess_piping_to_file.ts 158 | ``` 159 | -------------------------------------------------------------------------------- /node/import_maps.md: -------------------------------------------------------------------------------- 1 | ## Using import maps 2 | 3 | Deno supports [import maps](../linking_to_external_code/import_maps.md) which 4 | allow you to supply Deno with information about how to resolve modules that 5 | overrides the default behavior. Import maps are a web platform standard that is 6 | increasingly being included natively in browsers. They are specifically useful 7 | with adapting Node code to work well with Deno, as you can use import maps to 8 | map "bare" specifiers to a specific module. 9 | 10 | When coupled with Deno friendly [CDNs](./cdns.md) import maps can be a powerful 11 | tool in managing code and dependencies without need of a package management 12 | tool. 13 | 14 | ### Bare and extension-less specifiers 15 | 16 | Deno will only load a fully qualified module, including the extension. The 17 | import specifier needs to either be relative or absolute. Specifiers that are 18 | neither relative or absolute are often called "bare" specifiers. For example 19 | `"./lodash/index.js"` is a relative specifier and 20 | `https://cdn.skypack.dev/lodash` is an absolute specifier. Whereas `"lodash"` 21 | would be a bare specifier. 22 | 23 | Also Deno requires that for local modules, the module to load is fully 24 | resolve-able. When an extension is not present, Deno would have to "guess" what 25 | the author intended to be loaded. For example does `"./lodash"` mean 26 | `./lodash.js`, `./lodash.ts`, `./lodash.tsx`, `./lodash.jsx`, 27 | `./lodash/index.js`, `./lodash/index.ts`, `./lodash/index.jsx`, or 28 | `./lodash/index.tsx`? 29 | 30 | When dealing with remote modules, Deno allows the CDN/web server define whatever 31 | semantics around resolution the server wants to define. It just treats a URL, 32 | including its query string, as a "unique" module that can be loaded. It expects 33 | the CDN/web server to provide it with a valid media/content type to instruct 34 | Deno how to handle the file. More information on how media types impact how Deno 35 | handles modules can be found in the 36 | [Determining the type of file](../typescript/overview.md#determining-the-type-of-file) 37 | section of the manual. 38 | 39 | Node does have defined semantics for resolving specifiers, but they are complex, 40 | assume unfettered access to the local file system to query it. Deno has chosen 41 | not to go down that path. 42 | 43 | But, import maps can be used to provide some of the ease of the developer 44 | experience if you wish to use bare specifiers. For example, if we want to do the 45 | following in our code: 46 | 47 | ```ts, ignore 48 | import lodash from "lodash"; 49 | ``` 50 | 51 | We can accomplish this using an import map, and we don't even have to install 52 | the `lodash` package locally. We would want to create a JSON file (for example 53 | **import_map.json**) with the following: 54 | 55 | ```json 56 | { 57 | "imports": { 58 | "lodash": "https://cdn.skypack.dev/lodash" 59 | } 60 | } 61 | ``` 62 | 63 | And we would run our program like: 64 | 65 | ``` 66 | > deno run --import-map ./import_map.json example.ts 67 | ``` 68 | 69 | If you wanted to manage the versions in the import map, you could do this as 70 | well. For example if you were using Skypack CDN, you can used a 71 | [pinned URL](https://docs.skypack.dev/skypack-cdn/api-reference/pinned-urls-optimized) 72 | for the dependency in your import map. For example, to pin to lodash version 73 | 4.17.21 (and minified production ready version), you would do this: 74 | 75 | ```json 76 | { 77 | "imports": { 78 | "lodash": "https://cdn.skypack.dev/pin/lodash@v4.17.21-K6GEbP02mWFnLA45zAmi/mode=imports,min/optimized/lodash.js" 79 | } 80 | } 81 | ``` 82 | 83 | ### Overriding imports 84 | 85 | The other situation where import maps can be very useful is the situation where 86 | you have tried your best to make something work, but have failed. For example 87 | you are using an npm package which has a dependency on some code that just 88 | doesn't work under Deno, and you want to substitute another module that 89 | "polyfills" the incompatible APIs. 90 | 91 | For example, let's say we have a package that is using a version of the built-in 92 | `"fs"` module that we have a local module we want to replace it with when it 93 | tries to import it, but we want other code we are loading to use the standard 94 | library replacement module for `"fs"`. We would want to create an import map 95 | that looked something like this: 96 | 97 | ```json 98 | { 99 | "imports": { 100 | "fs": "https://deno.land/std@$STD_VERSION/node/fs.ts" 101 | }, 102 | "scopes": { 103 | "https://deno.land/x/example": { 104 | "fs": "./patched/fs.ts" 105 | } 106 | } 107 | } 108 | ``` 109 | 110 | Import maps can be very powerful, check out the official 111 | [standards README](https://github.com/WICG/import-maps#the-import-map) for more 112 | information. 113 | -------------------------------------------------------------------------------- /runtime/ffi_api.md: -------------------------------------------------------------------------------- 1 | ## Foreign Function Interface API 2 | 3 | As of Deno 1.13 and later, the FFI (foreign function interface) API allows users 4 | to call libraries written in native languages that support the C ABIs (Rust, 5 | C/C++, C#, Zig, Nim, Kotlin, etc) using `Deno.dlopen`. 6 | 7 | ### Usage 8 | 9 | Here's an example showing how to call a Rust function from Deno: 10 | 11 | ```rust 12 | // add.rs 13 | #[no_mangle] 14 | pub extern "C" fn add(a: isize, b: isize) -> isize { 15 | a + b 16 | } 17 | ``` 18 | 19 | Compile it to a C dynamic library (`libadd.so` on Linux): 20 | 21 | ```sh 22 | rustc --crate-type cdylib add.rs 23 | ``` 24 | 25 | In C you can write it as: 26 | 27 | ```c 28 | // add.c 29 | int add(int a, int b) { 30 | return a + b; 31 | } 32 | ``` 33 | 34 | And compile it: 35 | 36 | ```sh 37 | // unix 38 | cc -c -o add.o add.c 39 | cc -shared -W -o libadd.so add.o 40 | // Windows 41 | cl /LD add.c /link /EXPORT:libadd 42 | ``` 43 | 44 | Calling the library from Deno: 45 | 46 | ```typescript 47 | // ffi.ts 48 | 49 | // Determine library extension based on 50 | // your OS. 51 | let libSuffix = ""; 52 | switch (Deno.build.os) { 53 | case "windows": 54 | libSuffix = "dll"; 55 | break; 56 | case "darwin": 57 | libSuffix = "dylib"; 58 | break; 59 | case "linux": 60 | libSuffix = "so"; 61 | break; 62 | } 63 | 64 | const libName = `./libadd.${libSuffix}`; 65 | // Open library and define exported symbols 66 | const dylib = Deno.dlopen(libName, { 67 | "add": { parameters: ["isize", "isize"], result: "isize" }, 68 | }); 69 | 70 | // Call the symbol `add` 71 | const result = dylib.symbols.add(35, 34); // 69 72 | 73 | console.log(`Result from external addition of 35 and 34: ${result}`); 74 | ``` 75 | 76 | Run with `--allow-ffi` and `--unstable` flag: 77 | 78 | ```sh 79 | deno run --allow-ffi --unstable ffi.ts 80 | ``` 81 | 82 | ### Non-blocking FFI 83 | 84 | There are many use cases where users might want to run CPU-bound FFI functions 85 | in the background without blocking other tasks on the main thread. 86 | 87 | As of Deno 1.15, symbols can be marked `nonblocking` in `Deno.dlopen`. These 88 | function calls will run on a dedicated blocking thread and will return a 89 | `Promise` resolving to the desired `result`. 90 | 91 | Example of executing expensive FFI calls with Deno: 92 | 93 | ```c 94 | // sleep.c 95 | #ifdef _WIN32 96 | #include 97 | #else 98 | #include 99 | #endif 100 | 101 | int sleep(unsigned int ms) { 102 | #ifdef _WIN32 103 | Sleep(ms); 104 | #else 105 | struct timespec ts; 106 | ts.tv_sec = ms / 1000; 107 | ts.tv_nsec = (ms % 1000) * 1000000; 108 | nanosleep(&ts, NULL); 109 | #endif 110 | } 111 | ``` 112 | 113 | Calling it from Deno: 114 | 115 | ```typescript 116 | // nonblocking_ffi.ts 117 | const library = Deno.dlopen("./sleep.so", { 118 | sleep: { 119 | parameters: ["usize"], 120 | result: "void", 121 | nonblocking: true, 122 | }, 123 | }); 124 | 125 | library.symbols.sleep(500).then(() => console.log("After")); 126 | console.log("Before"); 127 | ``` 128 | 129 | Result: 130 | 131 | ```sh 132 | $ deno run --allow-ffi --unstable unblocking_ffi.ts 133 | Before 134 | After 135 | ``` 136 | 137 | ### Supported types 138 | 139 | Here's a list of types supported currently by the Deno FFI API. 140 | 141 | | FFI Type | C | Rust | 142 | | ------------ | ------------------------ | ----------- | 143 | | `i8` | `char` / `signed char` | `i8` | 144 | | `u8` | `unsigned char` | `u8` | 145 | | `i16` | `short int` | `i16` | 146 | | `u16` | `unsigned short int` | `u16` | 147 | | `i32` | `int` / `signed int` | `i32` | 148 | | `u32` | `unsigned int` | `u32` | 149 | | `i64` | `long long int` | `i64` | 150 | | `u64` | `unsigned long long int` | `u64` | 151 | | `usize` | `size_t` | `usize` | 152 | | `f32` | `float` | `f32` | 153 | | `f64` | `double` | `f64` | 154 | | `void` | `void` | `()` | 155 | | `pointer`[1] | `const uint8_t *` | `*const u8` | 156 | 157 | - [1] `pointer` type accepts both Typed Arrays and `Deno.UnsafePointer` as 158 | parameter, while it always returns the latter when used as result type. 159 | 160 | ### deno_bindgen 161 | 162 | [`deno_bindgen`](https://github.com/littledivy/deno_bindgen) is an external tool 163 | to simplify glue code generation of Deno FFI libraries written in Rust. 164 | 165 | It is similar to [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) in 166 | the Rust WASM ecosystem. 167 | 168 | Here's an example showing its usage: 169 | 170 | ```rust 171 | // mul.rs 172 | use deno_bindgen::deno_bindgen; 173 | 174 | #[deno_bindgen] 175 | struct Input { 176 | a: i32, 177 | b: i32, 178 | } 179 | 180 | #[deno_bindgen] 181 | fn mul(input: Input) -> i32 { 182 | input.a * input.b 183 | } 184 | ``` 185 | 186 | Run `deno_bindgen` to generate bindings. You can now directly import them into 187 | Deno: 188 | 189 | ```ts, ignore 190 | // mul.ts 191 | import { mul } from "./bindings/bindings.ts"; 192 | mul({ a: 10, b: 2 }); // 20 193 | ``` 194 | 195 | Any issues related to `deno_bindgen` should be reported at 196 | https://github.com/littledivy/deno_bindgen/issues 197 | -------------------------------------------------------------------------------- /toc.json: -------------------------------------------------------------------------------- 1 | { 2 | "introduction": { 3 | "name": "Introduction" 4 | }, 5 | "getting_started": { 6 | "name": "Getting Started", 7 | "children": { 8 | "installation": "Installation", 9 | "setup_your_environment": "Set up your environment", 10 | "first_steps": "First steps", 11 | "command_line_interface": "Command line interface", 12 | "configuration_file": "Configuration file", 13 | "permissions": "Permissions", 14 | "debugging_your_code": "Debugging your code" 15 | } 16 | }, 17 | "runtime": { 18 | "name": "The Runtime", 19 | "children": { 20 | "stability": "Stability", 21 | "program_lifecycle": "Program lifecycle", 22 | "permission_apis": "Permission APIs", 23 | "web_platform_apis": "Web Platform APIs", 24 | "http_server_apis": "HTTP Server APIs", 25 | "http_server_apis_low_level": "HTTP Server APIs (low level)", 26 | "location_api": "Location API", 27 | "web_storage_api": "Web Storage API", 28 | "workers": "Workers", 29 | "ffi_api": "Foreign Function Interface API" 30 | } 31 | }, 32 | "linking_to_external_code": { 33 | "name": "Linking to external code", 34 | "children": { 35 | "reloading_modules": "Reloading modules", 36 | "integrity_checking": "Integrity checking", 37 | "proxies": "Proxies", 38 | "private": "Private modules", 39 | "import_maps": "Import maps" 40 | } 41 | }, 42 | "node": { 43 | "name": "Interoperating with Node and NPM", 44 | "children": { 45 | "compatibility_mode": "Node compatibility mode", 46 | "std_node": "The std/node library", 47 | "cdns": "Packages from CDNs", 48 | "import_maps": "Using import maps", 49 | "faqs": "Frequently asked questions", 50 | "cheatsheet": "Node->Deno cheatsheet", 51 | "dnt": "dnt - Deno to Node Transform" 52 | } 53 | }, 54 | "typescript": { 55 | "name": "Using TypeScript", 56 | "children": { 57 | "overview": "Overview", 58 | "configuration": "Configuration", 59 | "types": "Types and type declarations", 60 | "migration": "Migrating to/from JavaScript", 61 | "runtime": "Runtime compiler APIs", 62 | "faqs": "Frequently asked questions" 63 | } 64 | }, 65 | "jsx_dom": { 66 | "name": "Using JSX and the DOM", 67 | "children": { 68 | "overview": "Overview", 69 | "jsx": "Configuring JSX", 70 | "linkedom": "Using LinkeDOM", 71 | "deno_dom": "Using deno-dom", 72 | "jsdom": "Using jsdom", 73 | "css": "Parsing CSS", 74 | "twind": "Using Twind" 75 | } 76 | }, 77 | "webassembly": { 78 | "name": "Using WebAssembly", 79 | "children": { 80 | "using_wasm": "Using WebAssembly in Deno", 81 | "using_streaming_wasm": "Using the streaming WebAssembly APIs", 82 | "wasm_resources": "Helpful resources" 83 | } 84 | }, 85 | "standard_library": { 86 | "name": "Standard library" 87 | }, 88 | "examples": { 89 | "name": "Examples", 90 | "children": { 91 | "hello_world": "Hello world", 92 | "import_export": "Import and export modules", 93 | "manage_dependencies": "Manage dependencies", 94 | "fetch_data": "Fetch data", 95 | "read_write_files": "Read and write files", 96 | "unix_cat": "Unix cat program", 97 | "http_server": "HTTP web server", 98 | "file_server": "File server", 99 | "tcp_echo": "TCP echo server", 100 | "subprocess": "Creating a subprocess", 101 | "os_signals": "OS signals", 102 | "file_system_events": "File system events", 103 | "module_metadata": "Module metadata" 104 | } 105 | }, 106 | "testing": { 107 | "name": "Testing", 108 | "children": { 109 | "assertions": "Assertions", 110 | "coverage": "Coverage", 111 | "documentation": "Documentation", 112 | "sanitizers": "Sanitizers" 113 | } 114 | }, 115 | "tools": { 116 | "name": "Tools", 117 | "children": { 118 | "script_installer": "Script installer", 119 | "formatter": "Formatter", 120 | "repl": "Read-eval-print-loop", 121 | "bundler": "Bundler", 122 | "compiler": "Compiling executables", 123 | "documentation_generator": "Documentation generator", 124 | "dependency_inspector": "Dependency inspector", 125 | "linter": "Linter", 126 | "task_runner": "Task runner", 127 | "vendor": "Vendoring dependencies", 128 | "benchmarker": "Benchmarking" 129 | } 130 | }, 131 | "continuous_integration": { 132 | "name": "Continuous integration" 133 | }, 134 | "vscode_deno": { 135 | "name": "Using Visual Studio Code", 136 | "children": { 137 | "testing_api": "Testing API" 138 | } 139 | }, 140 | "language_server": { 141 | "name": "Language Server", 142 | "children": { 143 | "overview": "Overview of the language server", 144 | "imports": "Import suggestions and intelligent registries", 145 | "testing_api": "Testing API" 146 | } 147 | }, 148 | "publishing": { 149 | "name": "Publishing Modules" 150 | }, 151 | "embedding_deno": { 152 | "name": "Embedding Deno" 153 | }, 154 | "help": { 155 | "name": "Help" 156 | }, 157 | "contributing": { 158 | "name": "Contributing", 159 | "children": { 160 | "building_from_source": "Building from source", 161 | "web_platform_tests": "Web platform tests", 162 | "style_guide": "Style guide", 163 | "architecture": "Architecture", 164 | "release_schedule": "Release schedule" 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /getting_started/command_line_interface.md: -------------------------------------------------------------------------------- 1 | ## Command line interface 2 | 3 | Deno is a command line program. You should be familiar with some simple commands 4 | having followed the examples thus far and already understand the basics of shell 5 | usage. 6 | 7 | There are multiple ways of viewing the main help text: 8 | 9 | ```shell 10 | # Using the subcommand. 11 | deno help 12 | 13 | # Using the short flag -- outputs the same as above. 14 | deno -h 15 | 16 | # Using the long flag -- outputs more detailed help text where available. 17 | deno --help 18 | ``` 19 | 20 | Deno's CLI is subcommand-based. The above commands should show you a list of 21 | subcommands supported, such as `deno bundle`. To see subcommand-specific help, 22 | for example for `bundle`, you can similarly run one of: 23 | 24 | ```shell 25 | deno help bundle 26 | deno bundle -h 27 | deno bundle --help 28 | ``` 29 | 30 | Detailed guides for each subcommand can be found [here](../tools.md). 31 | 32 | ### Script source 33 | 34 | Deno can grab the scripts from multiple sources, a filename, a url, and '-' to 35 | read the file from stdin. The latter is useful for integration with other 36 | applications. 37 | 38 | ```shell 39 | deno run main.ts 40 | deno run https://mydomain.com/main.ts 41 | cat main.ts | deno run - 42 | ``` 43 | 44 | ### Script arguments 45 | 46 | Separately from the Deno runtime flags, you can pass user-space arguments to the 47 | script you are running by specifying them **after** the script name: 48 | 49 | ```shell 50 | deno run main.ts a b -c --quiet 51 | ``` 52 | 53 | ```ts 54 | // main.ts 55 | console.log(Deno.args); // [ "a", "b", "-c", "--quiet" ] 56 | ``` 57 | 58 | **Note that anything passed after the script name will be passed as a script 59 | argument and not consumed as a Deno runtime flag.** This leads to the following 60 | pitfall: 61 | 62 | ```shell 63 | # Good. We grant net permission to net_client.ts. 64 | deno run --allow-net net_client.ts 65 | 66 | # Bad! --allow-net was passed to Deno.args, throws a net permission error. 67 | deno run net_client.ts --allow-net 68 | ``` 69 | 70 | Some see it as unconventional that: 71 | 72 | > a non-positional flag is parsed differently depending on its position. 73 | 74 | However: 75 | 76 | 1. This is the most logical and ergonomic way of distinguishing between runtime 77 | flags and script arguments. 78 | 2. This is, in fact, the same behaviour as that of any other popular runtime. 79 | - Try `node -c index.js` and `node index.js -c`. The first will only do a 80 | syntax check on `index.js` as per Node's `-c` flag. The second will 81 | _execute_ `index.js` with `-c` passed to `require("process").argv`. 82 | 83 | --- 84 | 85 | There exist logical groups of flags that are shared between related subcommands. 86 | We discuss these below. 87 | 88 | ### Watch mode 89 | 90 | You can supply the `--watch` flag to `deno run`, `deno test`, `deno bundle`, and 91 | `deno fmt` to enable the built-in file watcher. The files that are watched 92 | depend on the subcommand used: 93 | 94 | - for `deno run`, `deno test`, and `deno bundle` the entrypoint, and all local 95 | files the entrypoint(s) statically import(s) will be watched. 96 | - for `deno fmt` all local files and directories specified as command line 97 | arguments (or the working directory if no specific files/directories is 98 | passed) are watched. 99 | 100 | Whenever one of the watched files is changed on disk, the program will 101 | automatically be restarted / formatted / tested / bundled. 102 | 103 | ``` 104 | deno run --watch main.ts 105 | deno test --watch 106 | deno fmt --watch 107 | ``` 108 | 109 | ### Integrity flags (lock files) 110 | 111 | Affect commands which can download resources to the cache: `deno cache`, 112 | `deno run`, `deno test`, `deno bundle`, `deno doc`, and `deno compile`. 113 | 114 | ``` 115 | --lock Check the specified lock file 116 | --lock-write Write lock file. Use with --lock. 117 | ``` 118 | 119 | Find out more about these 120 | [here](../linking_to_external_code/integrity_checking.md). 121 | 122 | ### Cache and compilation flags 123 | 124 | Affect commands which can populate the cache: `deno cache`, `deno run`, 125 | `deno test`, `deno bundle`, `deno doc`, and `deno compile`. As well as the flags 126 | above, this includes those which affect module resolution, compilation 127 | configuration etc. 128 | 129 | ``` 130 | --config Load configuration file 131 | --import-map Load import map file 132 | --no-remote Do not resolve remote modules 133 | --reload= Reload source code cache (recompile TypeScript) 134 | --unstable Enable unstable APIs 135 | ``` 136 | 137 | ### Runtime flags 138 | 139 | Affect commands which execute user code: `deno run` and `deno test`. These 140 | include all of the above as well as the following. 141 | 142 | #### Permission flags 143 | 144 | These are listed [here](./permissions.md#permissions-list). 145 | 146 | #### Other runtime flags 147 | 148 | More flags which affect the execution environment. 149 | 150 | ``` 151 | --cached-only Require that remote dependencies are already cached 152 | --inspect= activate inspector on host:port ... 153 | --inspect-brk= activate inspector on host:port and break at ... 154 | --location Value of 'globalThis.location' used by some web APIs 155 | --prompt Fallback to prompt if required permission wasn't passed 156 | --seed Seed Math.random() 157 | --v8-flags= Set V8 command line options. For help: ... 158 | ``` 159 | -------------------------------------------------------------------------------- /getting_started/first_steps.md: -------------------------------------------------------------------------------- 1 | ## First steps 2 | 3 | This page contains some examples to teach you about the fundamentals of Deno. 4 | 5 | This document assumes that you have some prior knowledge of JavaScript, 6 | especially about `async`/`await`. If you have no prior knowledge of JavaScript, 7 | you might want to follow a guide 8 | [on the basics of JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript) 9 | before attempting to start with Deno. 10 | 11 | ### Hello World 12 | 13 | Deno is a runtime for JavaScript/TypeScript which tries to be web compatible and 14 | use modern features wherever possible. 15 | 16 | Browser compatibility means a `Hello World` program in Deno is the same as the 17 | one you can run in the browser: 18 | 19 | ```ts 20 | console.log("Welcome to Deno!"); 21 | ``` 22 | 23 | Try the program: 24 | 25 | ```shell 26 | deno run https://deno.land/std@$STD_VERSION/examples/welcome.ts 27 | ``` 28 | 29 | ### Making an HTTP request 30 | 31 | Many programs use HTTP requests to fetch data from a webserver. Let's write a 32 | small program that fetches a file and prints its contents out to the terminal. 33 | 34 | Just like in the browser you can use the web standard 35 | [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to 36 | make HTTP calls: 37 | 38 | ```ts 39 | const url = Deno.args[0]; 40 | const res = await fetch(url); 41 | 42 | const body = new Uint8Array(await res.arrayBuffer()); 43 | await Deno.stdout.write(body); 44 | ``` 45 | 46 | Let's walk through what this application does: 47 | 48 | 1. We get the first argument passed to the application, and store it in the 49 | `url` constant. 50 | 2. We make a request to the url specified, await the response, and store it in 51 | the `res` constant. 52 | 3. We parse the response body as an 53 | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), 54 | await the response, and convert it into a 55 | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) 56 | to store in the `body` constant. 57 | 4. We write the contents of the `body` constant to `stdout`. 58 | 59 | Try it out: 60 | 61 | ```shell 62 | deno run https://deno.land/std@$STD_VERSION/examples/curl.ts https://example.com 63 | ``` 64 | 65 | You will see this program returns an error regarding network access, so what did 66 | we do wrong? You might remember from the introduction that Deno is a runtime 67 | which is secure by default. This means you need to explicitly give programs the 68 | permission to do certain 'privileged' actions, such as access the network. 69 | 70 | Try it out again with the correct permission flag: 71 | 72 | ```shell 73 | deno run --allow-net=example.com https://deno.land/std@$STD_VERSION/examples/curl.ts https://example.com 74 | ``` 75 | 76 | ### Reading a file 77 | 78 | Deno also provides APIs which do not come from the web. These are all contained 79 | in the `Deno` global. You can find documentation for these APIs on 80 | [doc.deno.land](https://doc.deno.land/deno/stable/~/Deno). 81 | 82 | Filesystem APIs for example do not have a web standard form, so Deno provides 83 | its own API. 84 | 85 | In this program each command-line argument is assumed to be a filename, the file 86 | is opened, and printed to stdout. 87 | 88 | ```ts 89 | import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; 90 | const filenames = Deno.args; 91 | for (const filename of filenames) { 92 | const file = await Deno.open(filename); 93 | await copy(file, Deno.stdout); 94 | file.close(); 95 | } 96 | ``` 97 | 98 | The `copy()` function here actually makes no more than the necessary 99 | kernel→userspace→kernel copies. That is, the same memory from which data is read 100 | from the file, is written to stdout. This illustrates a general design goal for 101 | I/O streams in Deno. 102 | 103 | Try the program: 104 | 105 | ```shell 106 | # macOS / Linux 107 | deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/hosts 108 | 109 | # Windows 110 | deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts "C:\Windows\System32\Drivers\etc\hosts" 111 | ``` 112 | 113 | ### TCP server 114 | 115 | This is an example of a server which accepts connections on port 8080, and 116 | returns to the client anything it sends. 117 | 118 | ```ts 119 | import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts"; 120 | const hostname = "0.0.0.0"; 121 | const port = 8080; 122 | const listener = Deno.listen({ hostname, port }); 123 | console.log(`Listening on ${hostname}:${port}`); 124 | for await (const conn of listener) { 125 | copy(conn, conn); 126 | } 127 | ``` 128 | 129 | For security reasons, Deno does not allow programs to access the network without 130 | explicit permission. To allow accessing the network, use a command-line flag: 131 | 132 | ```shell 133 | deno run --allow-net https://deno.land/std@$STD_VERSION/examples/echo_server.ts 134 | ``` 135 | 136 | To test it, try sending data to it with `netcat` (or `telnet` on Windows): 137 | 138 | > Note for Windows users: netcat is not available on Windows. Instead you can 139 | > use the built-in telnet client. The telnet client is disabled in Windows by 140 | > default. It is easy to enable however: just follow the instructions 141 | > [on Microsoft TechNet](https://social.technet.microsoft.com/wiki/contents/articles/38433.windows-10-enabling-telnet-client.aspx) 142 | 143 | ```shell 144 | # Note for Windows users: replace the `nc` below with `telnet` 145 | $ nc localhost 8080 146 | hello world 147 | hello world 148 | ``` 149 | 150 | Like the `cat.ts` example, the `copy()` function here also does not make 151 | unnecessary memory copies. It receives a packet from the kernel and sends it 152 | back, without further complexity. 153 | 154 | ### More examples 155 | 156 | You can find more examples, like an HTTP file server, in the 157 | [Examples](../examples) chapter. 158 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We welcome and appreciate all contributions to Deno. 4 | 5 | This page serves as a helper to get you started on contributing. 6 | 7 | ## Projects 8 | 9 | There are numerous repositories in the [`denoland`](https://github.com/denoland) 10 | organization that are part of the Deno ecosystem. 11 | 12 | Repositories have different scopes, use different programming languages and have 13 | varying difficulty level when it comes to contributions. 14 | 15 | To help you decide which repository might be the best to start contributing 16 | (and/or falls into your interest), here's a short comparison (**languages in 17 | bold comprise most of the codebase**): 18 | 19 | ### [`deno`](https://github.com/denoland/deno) 20 | 21 | This is the main repository that provides the `deno` CLI. 22 | 23 | If you want to fix a bug or add a new feature to `deno` this is the repository 24 | you want to contribute to. 25 | 26 | Languages: **Rust**, **JavaScript** 27 | 28 | ### [`deno_std`](https://github.com/denoland/deno_std) 29 | 30 | The standard library for Deno. 31 | 32 | Languages: **TypeScript**, WebAssembly. 33 | 34 | ### [`dotland`](https://github.com/denoland/dotland) 35 | 36 | Frontend for official Deno webpage: https://deno.land/ 37 | 38 | Languages: **TypeScript**, TSX, CSS 39 | 40 | ### [`deno_lint`](https://github.com/denoland/deno_lint) 41 | 42 | Linter that powers `deno lint` subcommand. 43 | 44 | Languages: **Rust** 45 | 46 | ### [`deno_doc`](https://github.com/denoland/deno_doc) 47 | 48 | Documentation generator that powers `deno doc` subcommand and 49 | https://doc.deno.land 50 | 51 | Languages: **Rust** 52 | 53 | ### [`docland`](https://github.com/denoland/docland) 54 | 55 | Frontend for documentation generator: https://doc.deno.land 56 | 57 | Languages: **TypeScript**, TSX, CSS 58 | 59 | ### [`rusty_v8`](https://github.com/denoland/rusty_v8) 60 | 61 | Rust bindings for the V8 JavaScript engine. Very technical and low-level. 62 | 63 | Languages: **Rust** 64 | 65 | ### [`serde_v8`](https://github.com/denoland/serde_v8) 66 | 67 | Library that provides bijection layer between V8 and Rust objects. Based on 68 | [`serde`](https://crates.io/crates/serde) library. Very technical and low-level. 69 | 70 | Languages: **Rust** 71 | 72 | ### [`deno_docker`](https://github.com/denoland/deno_docker) 73 | 74 | Official Docker images for Deno. 75 | 76 | ## General remarks 77 | 78 | - Read the [style guide](./contributing/style_guide.md). 79 | 80 | - Please don't make [the benchmarks](https://deno.land/benchmarks) worse. 81 | 82 | - Ask for help in the [community chat room](https://discord.gg/deno). 83 | 84 | - If you are going to work on an issue, mention so in the issue comments 85 | _before_ you start working on the issue. 86 | 87 | - If you are going to work on a new feature, create an issue and discuss with 88 | other contributors _before_ you start working on the feature; we appreciate 89 | all contributions, but not all proposed features are getting accepted. We 90 | don't want you to spend hours working on a code that might not be accepted. 91 | 92 | - Please be professional in the forums. We follow 93 | [Rust's code of conduct](https://www.rust-lang.org/policies/code-of-conduct) 94 | (CoC). Have a problem? Email [ry@tinyclouds.org](mailto:ry@tinyclouds.org). 95 | 96 | ## Submitting a pull request 97 | 98 | Before submitting a PR to any of the repos, please make sure the following is 99 | done: 100 | 101 | 1. Give the PR a descriptive title. 102 | 103 | Examples of good PR title: 104 | 105 | - fix(std/http): Fix race condition in server 106 | - docs(console): Update docstrings 107 | - feat(doc): Handle nested re-exports 108 | 109 | Examples of bad PR title: 110 | 111 | - fix #7123 112 | - update docs 113 | - fix bugs 114 | 115 | 2. Ensure there is a related issue and it is referenced in the PR text. 116 | 3. Ensure there are tests that cover the changes. 117 | 118 | ### Submitting a PR to [`deno`](https://github.com/denoland/deno) 119 | 120 | Additionally to the above make sure that: 121 | 122 | 1. `cargo test` passes - this will run full test suite for `deno` including unit 123 | tests, integration tests and Web Platform Tests 124 | 125 | 1. Run `./tools/format.js` - this will format all of the code to adhere to the 126 | consistent style in the repository 127 | 128 | 1. Run `./tools/lint.js` - this will check Rust and JavaScript code for common 129 | mistakes and errors using `clippy` (for Rust) and `dlint` (for JavaScript) 130 | 131 | ## Submitting a PR to [`deno_std`](https://github.com/denoland/deno_std) 132 | 133 | Additionally to the above make sure that: 134 | 135 | 1. All of the code you wrote is in `TypeScript` (ie. don't use `JavaScript`) 136 | 137 | 1. `deno test --unstable --allow-all` passes - this will run full test suite for 138 | the standard library 139 | 140 | 1. Run `deno fmt` in the root of repository - this will format all of the code 141 | to adhere to the consistent style in the repository. 142 | 143 | 1. Run `deno lint` - this will check TypeScript code for common mistakes and 144 | errors. 145 | 146 | ## Documenting APIs 147 | 148 | It is important to document all public APIs and we want to do that inline with 149 | the code. This helps ensure that code and documentation are tightly coupled 150 | together. 151 | 152 | ### JavaScript and TypeScript 153 | 154 | All publicly exposed APIs and types, both via the `deno` module as well as the 155 | global/`window` namespace should have JSDoc documentation. This documentation is 156 | parsed and available to the TypeScript compiler, and therefore easy to provide 157 | further downstream. JSDoc blocks come just prior to the statement they apply to 158 | and are denoted by a leading `/**` before terminating with a `*/`. For example: 159 | 160 | ```ts 161 | /** A simple JSDoc comment */ 162 | export const FOO = "foo"; 163 | ``` 164 | 165 | Find more at: https://jsdoc.app/ 166 | 167 | ### Rust 168 | 169 | Use 170 | [this guide](https://doc.rust-lang.org/rustdoc/how-to-write-documentation.html) 171 | for writing documentation comments in Rust code. 172 | -------------------------------------------------------------------------------- /jsx_dom/jsx.md: -------------------------------------------------------------------------------- 1 | ## Configuring JSX in Deno 2 | 3 | Deno has built-in support for JSX in both `.jsx` files and `.tsx` files. JSX in 4 | Deno can be handy for server-side rendering or generating code for consumption 5 | in a browser. 6 | 7 | ### Default configuration 8 | 9 | The Deno CLI has a default configuration for JSX that is different than the 10 | defaults for `tsc`. Effectively Deno uses the following 11 | [TypeScript compiler](https://www.typescriptlang.org/docs/handbook/compiler-options.html) 12 | options by default: 13 | 14 | ```json 15 | { 16 | "compilerOptions": { 17 | "jsx": "react", 18 | "jsxFactory": "React.createElement", 19 | "jsxFragmentFactory": "React.Fragment" 20 | } 21 | } 22 | ``` 23 | 24 | ### JSX import source 25 | 26 | In React 17, the React team added what they called 27 | [the _new_ JSX transforms](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). 28 | This enhanced and modernized the API for JSX transforms as well as provided a 29 | mechanism to automatically import a JSX library into a module, instead of having 30 | to explicitly import it or make it part of the global scope. Generally this 31 | makes it easier to use JSX in your application. 32 | 33 | As of Deno 1.16, initial support for these transforms was added. Deno supports 34 | both the JSX import source pragma as well as configuring a JSX import source in 35 | a [configuration file](../getting_started/configuration_file.md). 36 | 37 | #### JSX runtime 38 | 39 | When using the automatic transforms, Deno will try to import a JSX runtime 40 | module that is expected to conform to the _new_ JSX API and is located at either 41 | `jsx-runtime` or `jsx-dev-runtime`. For example if a JSX import source is 42 | configured to `react`, then the emitted code will add this to the emitted file: 43 | 44 | ```jsx ignore 45 | import { jsx as jsx_ } from "react/jsx-runtime"; 46 | ``` 47 | 48 | Deno generally works off explicit specifiers, which means it will not try any 49 | other specifier at runtime than the one that is emitted. Which means to 50 | successfully load the JSX runtime, `"react/jsx-runtime"` would need to resolve 51 | to a module. Saying that, Deno supports remote modules, and most CDNs resolve 52 | the specifier easily. 53 | 54 | For example, if you wanted to use [Preact](https://preactjs.com/) from the 55 | [esm.sh](https://esm.sh/) CDN, you would use `https://esm.sh/preact` as the JSX 56 | import source, and esm.sh will resolve `https://esm.sh/preact/jsx-runtime` as a 57 | module, including providing a header in the response that tells Deno where to 58 | find the type definitions for Preact. 59 | 60 | #### Using the JSX import source pragma 61 | 62 | Whether you have a JSX import source configured for your project, or if you are 63 | using the default "legacy" configuration, you can add the JSX import source 64 | pragma to a `.jsx` or `.tsx` module, and Deno will respect it. 65 | 66 | The `@jsxImportSource` pragma needs to be in the leading comments of the module. 67 | For example to use Preact from esm.sh, you would do something like this: 68 | 69 | ```jsx ignore 70 | /** @jsxImportSource https://esm.sh/preact */ 71 | 72 | export function App() { 73 | return ( 74 |
75 |

Hello, world!

76 |
77 | ); 78 | } 79 | ``` 80 | 81 | #### Using JSX import source in a configuration file 82 | 83 | If you want to configure a JSX import source for a whole project, so you don't 84 | need to insert the pragma on each module, you can use the `"compilerOptions"` in 85 | a [configuration file](../getting_started/configuration_file.md) to specify 86 | this. For example if you were using Preact as your JSX library from esm.sh, you 87 | would configure the following, in the configuration file: 88 | 89 | ```jsonc 90 | { 91 | "compilerOptions": { 92 | "jsx": "react-jsx", 93 | "jsxImportSource": "https://esm.sh/preact" 94 | } 95 | } 96 | ``` 97 | 98 | #### Using an import map 99 | 100 | In situations where the import source plus `/jsx-runtime` or `/jsx-dev-runtime` 101 | is not resolvable to the correct module, an import map can be used to instruct 102 | Deno where to find the module. An import map can also be used to make the import 103 | source "cleaner". For example, if you wanted to use Preact from skypack.dev and 104 | have skypack.dev include all the type information, you could setup an import map 105 | like this: 106 | 107 | ```json 108 | { 109 | "imports": { 110 | "preact/jsx-runtime": "https://cdn.skypack.dev/preact/jsx-runtime?dts", 111 | "preact/jsx-dev-runtime": "https://cdn.skypack.dev/preact/jsx-dev-runtime?dts" 112 | } 113 | } 114 | ``` 115 | 116 | And then you could use the following pragma: 117 | 118 | ```jsx ignore 119 | /** @jsxImportSource preact */ 120 | ``` 121 | 122 | Or you could configure it in the compiler options: 123 | 124 | ```json 125 | { 126 | "compilerOptions": { 127 | "jsx": "react-jsx", 128 | "jsxImportSource": "preact" 129 | } 130 | } 131 | ``` 132 | 133 | You would then need to pass the `--import-map` option on the command line (along 134 | with the `--config` option is using a config file) or set the `deno.importMap` 135 | option (and `deno.config` option) in your IDE. 136 | 137 | #### Current limitations 138 | 139 | There are two current limitations of the support of the JSX import source: 140 | 141 | - A JSX module that does not have any imports or exports is not transpiled 142 | properly when type checking (see: 143 | [microsoft/TypeScript#46723](https://github.com/microsoft/TypeScript/issues/46723)). 144 | Errors will be seen at runtime about `_jsx` not being defined. To work around 145 | the issue, add `export {}` to the file or use the `--no-check` flag which will 146 | cause the module to be emitted properly. 147 | - Using `"jsx-reactdev"` compiler option is not supported with 148 | `--no-emit`/bundling/compiling (see: 149 | [swc-project/swc#2656](https://github.com/swc-project/swc/issues/2656)). 150 | Various runtime errors will occur about not being able to load `jsx-runtime` 151 | modules. To work around the issue, use the `"jsx-react"` compiler option 152 | instead, or don't use `--no-emit`, bundling or compiling. 153 | -------------------------------------------------------------------------------- /node/compatibility_mode.md: -------------------------------------------------------------------------------- 1 | ## Node compatibility mode 2 | 3 | Starting with v1.15 Deno provides Node compatibility mode that makes it possible 4 | to run a subset of programs authored for Node directly in Deno. Compatibility 5 | mode can be activated by passing `--compat` flag in CLI. 6 | 7 | > ⚠️ Using compatibility mode currently requires the `--unstable` flag. If you 8 | > intend to use CJS modules, the `--allow-read` flag is needed as well. 9 | 10 | > ⚠️ Package management is currently out of scope for Node compatibility mode. 11 | > For the time being we suggest to keep using your current solution (`npm`, 12 | > `yarn`, `pnpm`). 13 | 14 | ### Example 15 | 16 | [`eslint`](https://eslint.org/) is a very popular tool used by most of Node 17 | projects. Let's run `eslint` using Deno in Node compatibility mode. Assuming 18 | that `eslint` is already installed locally (either using `npm install eslint` or 19 | `yarn install eslint`) we can do so like: 20 | 21 | ```sh 22 | $ ls 23 | .eslintrc.json 24 | node_modules 25 | package.json 26 | test.js 27 | test.ts 28 | $ cat test.js 29 | function foo() {} 30 | 31 | $ cat test.ts 32 | function bar(): any {} 33 | 34 | $ deno run \ 35 | --compat --unstable \ 36 | --allow-read --allow-write=./ --allow-env \ 37 | node_modules/eslint/bin/eslint.js test.js test.ts 38 | 39 | /dev/test.js 40 | 1:10 warning 'foo' is defined but never used @typescript-eslint/no-unused-vars 41 | 1:16 error Unexpected empty function 'foo' @typescript-eslint/no-empty-function 42 | 43 | /dev/test.ts 44 | 1:10 warning 'bar' is defined but never used @typescript-eslint/no-unused-vars 45 | 1:17 warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any 46 | 1:21 error Unexpected empty function 'bar' @typescript-eslint/no-empty-function 47 | 48 | ✖ 5 problems (2 errors, 3 warnings) 49 | ``` 50 | 51 | > ⚠️ Notice that ESLint is run with limited set of permissions. We only give it 52 | > access to the read from the file system, write to current directory and access 53 | > environmental variables. Programs run in compatility mode are subject to 54 | > Deno's permission model. 55 | 56 | ### How does it work? 57 | 58 | When using compatibility mode there Deno does a few things behind the scenes: 59 | 60 | - Node globals are set up and made available in the global scope. That means 61 | that APIs like `process`, `global`, `Buffer`, `setImmediate` or 62 | `clearImmediate` are available just like in Node. This is done by executing 63 | [`std/node/global.ts`](https://doc.deno.land/https://deno.land/std/node/global.ts) 64 | on startup. 65 | 66 | - Node built-in modules are set up and made available to import statements and 67 | `require()` calls. Following calls will return appropriate Node modules 68 | polyfilled using [`std/node`](https://deno.land/std/node/): 69 | - `import fs from "fs";` 70 | - `import os from "node:os";` 71 | - `const path = require("path");` 72 | - `const http = require("node:http");` 73 | 74 | - Deno will support Node resolution algorithm so importing packages using "bare" 75 | specifiers will work. For details on how module resolution works check Node 76 | documentation on [CJS](https://nodejs.org/api/modules.html) and 77 | [ES](https://nodejs.org/api/esm.html) modules. 78 | 79 | ### Module resolution 80 | 81 | [CommonJS resolution](https://nodejs.org/api/modules.html) is implemented as in 82 | Node and there should be no observable differences. 83 | 84 | [ES module resolution](https://nodejs.org/api/esm.html) is implemented on top of 85 | Deno's regular ESM resolution, leading to a few additional properties compared 86 | to Node: 87 | 88 | - In addition to `file:` and `data:` URL schemes supported in Node; `http:`, 89 | `https:` and `blob:` URL schemes will work in the same way if you used Deno 90 | without compatibility mode. 91 | 92 | - Import maps are supported in the same way if you used Deno without 93 | compatibility mode. When resolving "bare" specifiers Deno will first try to 94 | resolve them using import map (if one is provided using `--import-map` flag). 95 | Bare specifiers starting with `node:` prefix are extempt from this rule. 96 | 97 | - Deno respects 98 | ["Conditional exports"](https://nodejs.org/api/packages.html#conditional-exports) 99 | field in `package.json`; in addition to conditions recognized by Node, 100 | `"deno"` condition can be used. This property is useful to the package authors 101 | who want to provide separate entrypoint optimized for use with Deno. As an 102 | example, imagine that your package uses `node-fetch`. By providing a 103 | conditional `"deno"` export, you can add an entrypoint that doesn't depend on 104 | `node-fetch` and instead uses built-in `fetch` API in Deno. 105 | 106 | ### Node built-in modules 107 | 108 | Following built-in Node modules are currently supported: 109 | 110 | - `assert` (_partly_) 111 | - `assert/strict` (_partly_) 112 | - `buffer` 113 | - `console` (_partly_) 114 | - `constants` 115 | - `crypto` (_partly_) 116 | - `child_process` (_partly_) 117 | - `dns` (_partly_) 118 | - `events` 119 | - `fs` (_partly_) 120 | - `fs/promises` (_partly_) 121 | - `http` (_partly_) 122 | - `module` 123 | - `net` (_partly_) 124 | - `os` (_partly_) 125 | - `path` 126 | - `perf_hooks` (_partly_) 127 | - `process` (_partly_) 128 | - `querystring` 129 | - `readline` (_partly_) 130 | - `stream` 131 | - `string_decoder` 132 | - `sys` (_partly_) 133 | - `timers` 134 | - `timers/promises` 135 | - `tty` (_partly_) 136 | - `url` (_partly_) 137 | - `util` (_partly_) 138 | - `worker_threads` (_partly_) 139 | 140 | Following modules are not yet implemented: 141 | 142 | - `cluster` 143 | - `dgram` 144 | - `http2` 145 | - `https` 146 | - `repl` 147 | - `tls` 148 | - `vm` 149 | - `zlib` 150 | 151 | If you try to run Node code that requires any of the not implemented modules, 152 | please open an issue in https://github.com/denoland/deno_std/issues with example 153 | code. 154 | 155 | ### TypeScript support 156 | 157 | Currently, the compatibility mode does not support TypeScript. 158 | 159 | In the upcoming releases we plan to add support for a `types` field in 160 | `package.json`, to automatically lookup types and use them during type checking. 161 | 162 | In the long term, we'd like to provide ability to consume TypeScript code 163 | authored for the Node runtime. 164 | -------------------------------------------------------------------------------- /node/std_node.md: -------------------------------------------------------------------------------- 1 | ## The `std/node` library 2 | 3 | > ⚠️ Starting with v1.15 Deno provides a compatibility mode, that allows to 4 | > emulate Node environment and consume code authored for Node directly. See 5 | > [Node compatibility mode](./compatibility_mode.md) chapter for details. 6 | 7 | The `std/node` part of the Deno standard library is a Node compatibility layer. 8 | Its primary focus is providing "polyfills" for Node's 9 | [built-in modules](https://github.com/denoland/deno_std/tree/main/node#supported-builtins). 10 | It also provides a mechanism for loading CommonJS modules into Deno. 11 | 12 | The library is most useful when trying to use your own or private code that was 13 | written for Node. If you are trying to consume public npm packages, you are 14 | likely to get a better result using a [CDN](./cdns.md). 15 | 16 | ### Node built-in modules 17 | 18 | The standard library provides several "replacement" modules for Node built-in 19 | modules. These either replicate the functionality of the built-in or they call 20 | the Deno native APIs, returning an interface that is compatible with Node. 21 | 22 | The standard library provides modules for the following built-ins: 23 | 24 | - [`assert`](https://doc.deno.land/https://deno.land/std/node/assert.ts) 25 | (_partly_) 26 | - [`assert/strict`](https://doc.deno.land/https://deno.land/std/node/assert/strict.ts) 27 | (_partly_) 28 | - [`buffer`](https://doc.deno.land/https://deno.land/std/node/buffer.ts) 29 | - [`console`](https://doc.deno.land/https://deno.land/std/node/console.ts) 30 | (_partly_) 31 | - [`constants`](https://doc.deno.land/https://deno.land/std/node/constants.ts) 32 | - [`crypto`](https://doc.deno.land/https://deno.land/std/node/crypto.ts) 33 | (_partly_) 34 | - [`child_process`](https://doc.deno.land/https://deno.land/std/node/child_process.ts) 35 | (_partly_) 36 | - [`dns`](https://doc.deno.land/https://deno.land/std/node/dns.ts) (_partly_) 37 | - [`events`](https://doc.deno.land/https://deno.land/std/node/events.ts) 38 | - [`fs`](https://doc.deno.land/https://deno.land/std/node/fs.ts) (_partly_) 39 | - [`fs/promises`](https://doc.deno.land/https://deno.land/std/node/fs/promises.ts) 40 | (_partly_) 41 | - [`http`](https://doc.deno.land/https://deno.land/std/node/http.ts) (_partly_) 42 | - [`module`](https://doc.deno.land/https://deno.land/std/node/module.ts) 43 | - [`net`](https://doc.deno.land/https://deno.land/std/node/net.ts) (_partly_) 44 | - [`os`](https://doc.deno.land/https://deno.land/std/node/os.ts) (_partly_) 45 | - [`path`](https://doc.deno.land/https://deno.land/std/node/path.ts) 46 | - [`perf_hooks`](https://doc.deno.land/https://deno.land/std/node/perf_hooks.ts) 47 | (_partly_) 48 | - [`process`](https://doc.deno.land/https://deno.land/std/node/process.ts) 49 | (_partly_) 50 | - [`querystring`](https://doc.deno.land/https://deno.land/std/node/querystring.ts) 51 | - [`readline`](https://doc.deno.land/https://deno.land/std/node/readline.ts) 52 | (_partly_) 53 | - [`stream`](https://doc.deno.land/https://deno.land/std/node/stream.ts) 54 | - [`string_decoder`](https://doc.deno.land/https://deno.land/std/node/string_decoder.ts) 55 | - [`sys`](https://doc.deno.land/https://deno.land/std/node/sys.ts) (_partly_) 56 | - [`timers`](https://doc.deno.land/https://deno.land/std/node/timers.ts) 57 | - [`timers/promises`](https://doc.deno.land/https://deno.land/std/node/timers/promises.ts) 58 | - [`tty`](https://doc.deno.land/https://deno.land/std/node/tty.ts) (_partly_) 59 | - [`url`](https://doc.deno.land/https://deno.land/std/node/url.ts) (_partly_) 60 | - [`util`](https://doc.deno.land/https://deno.land/std/node/util.ts) (_partly_) 61 | - [`worker_threads`](https://doc.deno.land/https://deno.land/std/node/worker_threads.ts) 62 | 63 | Following modules are not yet implemented: 64 | 65 | - `cluster` 66 | - `dgram` 67 | - `http2` 68 | - `https` 69 | - `repl` 70 | - `tls` 71 | - `vm` 72 | - `zlib` 73 | 74 | If you try to run a Node code that requires any of the not implemented modules, 75 | please open an issue in https://github.com/denoland/deno_std/issues with example 76 | code. 77 | 78 | In addition, there is the 79 | [`std/node/global.ts`](https://doc.deno.land/https://deno.land/std/node/global.ts) 80 | module which provides some of the Node globals like `global`, `process`, and 81 | `Buffer`. 82 | 83 | If you want documentation for any of the modules, you can simply type `deno doc` 84 | and the URL of the module in your terminal: 85 | 86 | ``` 87 | > deno doc https://deno.land/std/fs/move.ts 88 | ``` 89 | 90 | ### Loading CommonJS modules 91 | 92 | Deno only supports natively loading ES Modules, but a lot of Node code is still 93 | written in the CommonJS format. As mentioned above, for public npm packages, it 94 | is often better to use a CDN to transpile CommonJS modules to ES Modules for 95 | consumption by Deno. Not only do you get reliable conversion plus all the 96 | dependency resolution and management without requiring a package manager to 97 | install the packages on your local machine, you get the advantages of being able 98 | to share your code easier without requiring other users to setup some of the 99 | Node infrastructure to consume your code with Node. 100 | 101 | That being said, the built-in Node module `"module"` provides a function named 102 | `createRequire()` which allows you to create a Node compatible `require()` 103 | function which can be used to load CommonJS modules, as well as use the same 104 | resolution logic that Node uses when trying to load a module. `createRequire()` 105 | will also install the Node globals for you. 106 | 107 | Example usage would look like this: 108 | 109 | ```ts, ignore 110 | import { createRequire } from "https://deno.land/std@$STD_VERSION/node/module.ts"; 111 | 112 | // import.meta.url will be the location of "this" module (like `__filename` in 113 | // Node), and then serve as the root for your "package", where the 114 | // `package.json` is expected to be, and where the `node_modules` will be used 115 | // for resolution of packages. 116 | const require = createRequire(import.meta.url); 117 | 118 | // Loads the built-in module Deno "replacement": 119 | const path = require("path"); 120 | 121 | // Loads a CommonJS module (without specifying the extension): 122 | const cjsModule = require("./my_mod"); 123 | 124 | // Uses Node resolution in `node_modules` to load the package/module. The 125 | // package would need to be installed locally via a package management tool 126 | // like npm: 127 | const leftPad = require("left-pad"); 128 | ``` 129 | 130 | When modules are loaded via the created `require()`, they are executed in a 131 | context which is similar to a Node context, which means that a lot of code 132 | written targeting Node will work. 133 | -------------------------------------------------------------------------------- /getting_started/permissions.md: -------------------------------------------------------------------------------- 1 | ## Permissions 2 | 3 | Deno is secure by default. Therefore, unless you specifically enable it, a 4 | program run with Deno has no file, network, or environment access. Access to 5 | security sensitive functionality requires that permissions have been granted to 6 | an executing script through command line flags, or a runtime permission prompt. 7 | 8 | For the following example `mod.ts` has been granted read-only access to the file 9 | system. It cannot write to the file system, or perform any other security 10 | sensitive functions. 11 | 12 | ```shell 13 | deno run --allow-read mod.ts 14 | ``` 15 | 16 | ### Permissions list 17 | 18 | The following permissions are available: 19 | 20 | - **--allow-env=\** Allow environment access for things like getting 21 | and setting of environment variables. Since Deno 1.9, you can specify an 22 | optional, comma-separated list of environment variables to provide an 23 | allow-list of allowed environment variables. 24 | - **--allow-hrtime** Allow high-resolution time measurement. High-resolution 25 | time can be used in timing attacks and fingerprinting. 26 | - **--allow-net=\** Allow network access. You can specify an 27 | optional, comma-separated list of IP addresses or hostnames (optionally with 28 | ports) to provide an allow-list of allowed network addresses. 29 | - **--allow-ffi** Allow loading of dynamic libraries. Be aware that dynamic 30 | libraries are not run in a sandbox and therefore do not have the same security 31 | restrictions as the Deno process. Therefore, use with caution. Please note 32 | that --allow-ffi is an unstable feature. 33 | - **--allow-read=\** Allow file system read access. You can specify 34 | an optional, comma-separated list of directories or files to provide an 35 | allow-list of allowed file system access. 36 | - **--allow-run=\** Allow running subprocesses. Since Deno 1.9, You 37 | can specify an optional, comma-separated list of subprocesses to provide an 38 | allow-list of allowed subprocesses. Be aware that subprocesses are not run in 39 | a sandbox and therefore do not have the same security restrictions as the Deno 40 | process. Therefore, use with caution. 41 | - **--allow-write=\** Allow file system write access. You can 42 | specify an optional, comma-separated list of directories or files to provide 43 | an allow-list of allowed file system access. 44 | - **-A, --allow-all** Allow all permissions. This enables all security sensitive 45 | functions. Use with caution. 46 | 47 | ### Configurable permissions 48 | 49 | Some permissions allow you to grant access to a specific list of entities 50 | (files, servers, etc) rather than to everything. 51 | 52 | #### File system access 53 | 54 | This example restricts file system access by allowing read-only access to the 55 | `/usr` directory. In consequence the execution fails as the process was 56 | attempting to read a file in the `/etc` directory: 57 | 58 | ```shell 59 | $ deno run --allow-read=/usr https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd 60 | error: Uncaught PermissionDenied: read access to "/etc/passwd", run again with the --allow-read flag 61 | ► $deno$/dispatch_json.ts:40:11 62 | at DenoError ($deno$/errors.ts:20:5) 63 | ... 64 | ``` 65 | 66 | Try it out again with the correct permissions by allowing access to `/etc` 67 | instead: 68 | 69 | ```shell 70 | deno run --allow-read=/etc https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd 71 | ``` 72 | 73 | `--allow-write` works the same as `--allow-read`. 74 | 75 | > Note for Windows users: the `/etc` and `/usr` directories and the 76 | > `/etc/passwd` file do not exist on Windows. If you want to run this example 77 | > yourself, replace `/etc/passwd` with `C:\Windows\System32\Drivers\etc\hosts`, 78 | > and `/usr` with `C:\Users`. 79 | 80 | #### Network access 81 | 82 | ```js 83 | // fetch.js 84 | const result = await fetch("https://deno.land/"); 85 | ``` 86 | 87 | This is an example of how to allow network access to specific hostnames or ip 88 | addresses, optionally locked to a specified port: 89 | 90 | ```shell 91 | # Multiple hostnames, all ports allowed 92 | deno run --allow-net=github.com,deno.land fetch.js 93 | 94 | # A hostname at port 80: 95 | deno run --allow-net=deno.land:80 fetch.js 96 | 97 | # An ipv4 address on port 443 98 | deno run --allow-net=1.1.1.1:443 fetch.js 99 | 100 | # A ipv6 address, all ports allowed 101 | deno run --allow-net=[2606:4700:4700::1111] fetch.js 102 | ``` 103 | 104 | If `fetch.js` tries to establish network connections to any hostname or IP not 105 | explicitly allowed, the relevant call will throw an exception. 106 | 107 | Allow net calls to any hostname/ip: 108 | 109 | ```shell 110 | deno run --allow-net fetch.js 111 | ``` 112 | 113 | #### Environment variables 114 | 115 | ```js 116 | // env.js 117 | Deno.env.get("HOME"); 118 | ``` 119 | 120 | This is an example of how to allow access to environment variables: 121 | 122 | ```shell 123 | # Allow all environment variables 124 | deno run --allow-env env.js 125 | 126 | # Allow access to only the HOME env var 127 | deno run --allow-env=HOME env.js 128 | ``` 129 | 130 | > Note for Windows users: environment variables are case insensitive on Windows, 131 | > so Deno also matches them case insensitively (on Windows only). 132 | 133 | #### Subprocess permissions 134 | 135 | Subprocesses are very powerful, and can be a little scary: they access system 136 | resources regardless of the permissions you granted to the Deno process that 137 | spawns them. The `cat` program on unix systems can be used to read files from 138 | disk. If you start this program through the `Deno.run` API it will be able to 139 | read files from disk even if the parent Deno process can not read the files 140 | directly. This is often referred to as privilege escalation. 141 | 142 | Because of this, make sure you carefully consider if you want to grant a program 143 | `--allow-run` access: it essentially invalidates the Deno security sandbox. If 144 | you really need to spawn a specific executable, you can reduce the risk by 145 | limiting which programs a Deno process can start by passing specific executable 146 | names to the `--allow-run` flag. 147 | 148 | ```js 149 | // run.js 150 | const proc = Deno.run({ cmd: ["whoami"] }); 151 | ``` 152 | 153 | ```shell 154 | # Allow only spawning a `whoami` subprocess: 155 | deno run --allow-run=whoami run.js 156 | 157 | # Allow running any subprocess: 158 | deno run --allow-run run.js 159 | ``` 160 | 161 | You can only limit the executables that are allowed; if permission is granted to 162 | execute it then any parameters can be passed. For example if you pass 163 | `--allow-run=cat` then the user can use `cat` to read any file. 164 | 165 | ### Conference 166 | 167 | Permission flags were explained by Ryan Dahl in his 2020 talk about the Deno 168 | security model at Speakeasy JS: 169 | https://www.youtube.com/watch?v=r5F6dekUmdE#t=34m57 170 | --------------------------------------------------------------------------------