Woongjae Lee
NHN Dooray - Frontend Team
Concept & Architecture, Getting Started, The Runtime, Runtime API, Tools, Testing, Deno Standard Modules, Examples, Third Party Modules
API Server Project
install mysql
nessie - A database migration tool for deno.
oak - A middleware framework for Deno's http server, including a router middleware.
denon - denon is the deno replacement for nodemon providing a feature packed and easy to use experience.
bcrypt - BCrypt support for hashing and checking passwords
djwt - The absolute minimum to make JSON Web Tokens on deno. Based on JWT and JWS specifications.
dotenv - Dotenv handling for deno.
Lead Software Engineer | Studio XID, Inc.
Microsoft MVP (2017 ~)
Deno Korea User Group 4th member
TypeScript Korea User Group Organizer
Marktube (Youtube)
1-1) Deno 의 탄생
1-2) Deno 설치하기
1-3) Deno CLI
1-4) deno run
1-5) deno info & cache
1-6) deno bundle
1-7) deno doc
1-8) deno install
1-9) Module Integrity checking
1-10) dependency inspector
1-11) code formatter & linter
1-12) deno types
1-13) Security & Permission
1-14) tsconfig.json
JavaScript runtime built on
2009
2018
A secure JavaScript/TypeScript runtime
built with V8, Rust, and Tokio
10 Things I Regret About Node.js
Ryan Dahl
JSConf EU 2018
2018.06
I Love TypeScript
Not sticking with Promises
Promises 를 밀었으면, 커뮤니티가 더 빨리 async / await 로 진보하지 않았을까
Security
보안에 신경 쓰지 못한 것에 대한 후회
The Build System (GYP)
GYP => GN 으로 가지 못한 것과 FFI 를 제공하지 못한 것에 대한 후회
package.json
npm 에 의존하도록 만든 것과 불필요한 정보들까지 가져오는 것에 대한 후회
node_modules
모듈을 가져오는 것이 어렵고, 브라우저에서 사용하는 방법과도 맞지 않아 어려워진 것에 대한 후회
require("module") without the extension ".js"
브라우저에서의 표준과 달라서 모듈을 쓸때, 사용자의 의도를 파악하기 어려운 것에 대한 후회
index.js
index.html 을 따라했지만, 모듈 로딩 시스템이 더 복잡해짐
➜ curl -fsSL https://deno.land/x/install/install.sh | sh
######################################################################## 100.0%
Deno was installed successfully to /Users/mark/.deno/bin/deno
Manually add the directory to your $HOME/.bash_profile (or similar)
export PATH="/Users/mark/.deno/bin:$PATH"
Run '/Users/mark/.deno/bin/deno --help' to get started
➜ curl -fsSL https://deno.land/x/install/install.sh | sh -s v1.0.0
➜ /Users/mark/.deno/bin/deno --help
# deno
export DENO_INSTALL="/Users/mark/.deno"
export PATH="$DENO_INSTALL/bin:$PATH"
➜ deno upgrade
Checking for latest version
Version has been found
Deno is upgrading to version 1.1.0
downloading https://github.com/denoland/deno/releases/download/v1.1.0/deno-x86_64-apple-darwin.zip
downloading https://github-production-release-asset-2e65be.s3.amazonaws.com/133442384/82737080-acd0-11ea-8397-c8f441f19bfa?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20200613%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200613T155009Z&X-Amz-Expires=300&X-Amz-Signature=dbe2eaad2e51bcbe2e88db96eefb40cec45b062ceb8476e6bfa7850f6531d7ef&X-Amz-SignedHeaders=host&actor_id=0&repo_id=133442384&response-content-disposition=attachment%3B%20filename%3Ddeno-x86_64-apple-darwin.zip&response-content-type=application%2Foctet-stream
Archive: /var/folders/6j/z282xrxj1cl9hwjqkxnzsrs40000gn/T/.tmpxCXahR/deno.zip
inflating: deno
Upgrade done successfully
➜ deno upgrade --version 1.1.0
Version 1.1.0 is already installed
➜ deno -V
deno 1.12.0
➜ deno --help
deno --help
SUBCOMMANDS:
bundle Bundle module and dependencies into single file
cache Cache the dependencies
compile UNSTABLE: Compile the script into a self contained executable
completions Generate shell completions
coverage Print coverage reports
doc Show documentation for a module
eval Eval script
fmt Format source files
help Prints this message or the help of the given subcommand(s)
info Show info about cache or info related to source file
install Install script as an executable
lint Lint source files
lsp Start the language server
repl Read Eval Print Loop
run Run a JavaScript or TypeScript program
test Run tests
types Print runtime TypeScript declarations
upgrade Upgrade deno executable to given version
➜ deno help bundle
➜ deno bundle --help
➜ deno help upgrade (deno upgrade --help)
deno-upgrade
Upgrade deno executable to the given version.
Defaults to latest.
The version is downloaded from
https://github.com/denoland/deno/releases
and is used to replace the current executable.
If you want to not replace the current Deno executable but instead download an
update to a different location, use the --output flag
deno upgrade --output $HOME/my_deno
USAGE:
deno upgrade [OPTIONS]
OPTIONS:
--canary Upgrade to canary builds
--cert <FILE> Load certificate authority from PEM encoded file
--dry-run Perform all checks without replacing old exe
-f, --force Replace current exe even if not out-of-date
-h, --help Prints help information
-L, --log-level <log-level> Set log level [possible values: debug, info]
--output <output> The path to output the updated version to
-q, --quiet Suppress diagnostic output
--unstable Enable unstable features and APIs
--version <version> The version to upgrade to
➜ deno help repl
deno-repl
Read Eval Print Loop
USAGE:
deno repl [OPTIONS]
OPTIONS:
--cached-only Require that remote dependencies are already cached
--cert <FILE> Load certificate authority from PEM encoded file
-c, --config <FILE> Load tsconfig.json configuration file
-h, --help Prints help information
--import-map <FILE> Load import map file
--inspect=<HOST:PORT> Activate inspector on host:port (default: 127.0.0.1:9229)
--inspect-brk=<HOST:PORT> Activate inspector on host:port and break at start of user script
--location <HREF> Value of 'globalThis.location' used by some web APIs
--lock <FILE> Check the specified lock file
--lock-write Write lock file (use with --lock)
-L, --log-level <log-level> Set log level [possible values: debug, info]
--no-check Skip type checking modules
--no-remote Do not resolve remote modules
-q, --quiet Suppress diagnostic output
-r, --reload=<CACHE_BLOCKLIST> Reload source code cache (recompile TypeScript)
--seed <NUMBER> Seed Math.random()
--unstable Enable unstable features and APIs
--v8-flags=<v8-flags> Set V8 command line options (for help: --v8-flags=--help)
➜ deno repl
Deno 1.1.0
exit using ctrl+d or close()
> console.log('Hello');
Hello
undefined
> const a = 39;
undefined
> a
39
> type S = string;
Uncaught SyntaxError: Unexpected identifier
at evaluate ($deno$/repl.ts:54:34)
at Object.replLoop ($deno$/repl.ts:156:13)
>
➜ deno help run
deno-run
Run a JavaScript or TypeScript program
By default all programs are run in sandbox without access to disk, network or
ability to spawn subprocesses.
deno run https://deno.land/std/examples/welcome.ts
Grant all permissions:
deno run -A https://deno.land/std/http/file_server.ts
Grant permission to read from disk and listen to network:
deno run --allow-read --allow-net https://deno.land/std/http/file_server.ts
Grant permission to read allow-listed files from disk:
deno run --allow-read=/etc https://deno.land/std/http/file_server.ts
Deno allows specifying the filename '-' to read the file from stdin.
curl https://deno.land/std/examples/welcome.ts | deno run -
USAGE:
deno run [OPTIONS] <SCRIPT_ARG>...
OPTIONS:
-A, --allow-all Allow all permissions
--allow-env=<allow-env> Allow environment access
--allow-hrtime Allow high resolution time measurement
--allow-net=<allow-net> Allow network access
--allow-plugin Allow loading plugins
--allow-read=<allow-read> Allow file system read access
--allow-run=<allow-run> Allow running subprocesses
--allow-write=<allow-write> Allow file system write access
--cached-only Require that remote dependencies are already cached
--cert <FILE> Load certificate authority from PEM encoded file
-c, --config <FILE> Load tsconfig.json configuration file
-h, --help Prints help information
--import-map <FILE> Load import map file
--inspect=<HOST:PORT> Activate inspector on host:port (default: 127.0.0.1:9229)
--inspect-brk=<HOST:PORT> Activate inspector on host:port and break at start of user script
--location <HREF> Value of 'globalThis.location' used by some web APIs
--lock <FILE> Check the specified lock file
--lock-write Write lock file (use with --lock)
-L, --log-level <log-level> Set log level [possible values: debug, info]
--no-check Skip type checking modules
--no-remote Do not resolve remote modules
--prompt Fallback to prompt if required permission wasn't passed
-q, --quiet Suppress diagnostic output
-r, --reload=<CACHE_BLOCKLIST> Reload source code cache (recompile TypeScript)
--seed <NUMBER> Seed Math.random()
--unstable Enable unstable features and APIs
--v8-flags=<v8-flags> Set V8 command line options (for help: --v8-flags=--help)
--watch UNSTABLE: Watch for file changes and restart process automatically
ARGS:
<SCRIPT_ARG>... Script arg
➜ deno help run
deno-run
Run a JavaScript or TypeScript program
By default all programs are run in sandbox without access to disk, network or
ability to spawn subprocesses.
deno run https://deno.land/std/examples/welcome.ts
Grant all permissions:
deno run -A https://deno.land/std/http/file_server.ts
Grant permission to read from disk and listen to network:
deno run --allow-read --allow-net https://deno.land/std/http/file_server.ts
Grant permission to read allow-listed files from disk:
deno run --allow-read=/etc https://deno.land/std/http/file_server.ts
Deno allows specifying the filename '-' to read the file from stdin.
curl https://deno.land/std/examples/welcome.ts | deno run -
~/FastCampus/deno2021
➜ echo "console.log('Hello Deno');" >> welcome.ts
~/FastCampus/deno2021
➜ cat welcome.ts
console.log('Hello Deno');
~/FastCampus/deno2021
➜ deno run welcome.ts
Compile file:///Users/mark/FastCampus/deno2021/welcome.ts => 파일을 컴파일
Hello Deno => 실행
~/FastCampus/deno2021
➜ deno run ./welcome.ts
Hello Deno => 실행
~/FastCampus/deno2021
➜ deno run /Users/mark/FastCampus/deno2021/welcome.ts
Hello Deno => 실행
~/FastCampus/deno2021
➜ deno run https://deno.land/std/examples/welcome.ts
Download https://deno.land/std/examples/welcome.ts => 파일을 다운로드
Warning Implicitly using master branch https://deno.land/std/examples/welcome.ts
=> 다운받은 url 이 명시적인 master branch 가 아님을 의미
Compile https://deno.land/std/examples/welcome.ts => 파일을 컴파일
Welcome to Deno 🦕 => 실행
~/FastCampus/deno2021 took 2s
➜ deno run https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts
Download https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts => 파일을 다운로드
Compile https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts => 파일을 컴파일
Welcome to Deno 🦕 => 실행
~/FastCampus/deno2021
➜ deno run https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts
Welcome to Deno 🦕 => 실행
~/FastCampus/deno2021
➜ deno run -r welcome.ts
Compile file:///Users/mark/FastCampus/deno2021/welcome.ts => 파일을 다시 컴파일
Hello Deno => 실행
~/FastCampus/deno2021
➜ deno run -r https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts
Download https://deno.land/std/examples/welcome.ts => 파일을 다시 다운로드
Compile https://deno.land/std/examples/welcome.ts => 파일을 다시 컴파일
Welcome to Deno 🦕 => 실행
~/FastCampus/deno2021
➜ deno info https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts
local: /Users/mark/Library/Caches/deno/deps/https/raw.githubusercontent.com/b4d51570d044a9e212325ea0df4614a665802a9a1e17256636d884301fa80597
type: TypeScript
compiled: /Users/mark/Library/Caches/deno/gen/https/raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts.js
map: /Users/mark/Library/Caches/deno/gen/https/raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts.js.map
deps:
https://raw.githubusercontent.com/denoland/deno/master/std/examples/welcome.ts
~/FastCampus/deno2021
➜ deno info
DENO_DIR location: "/Users/mark/Library/Caches/deno"
Remote modules cache: "/Users/mark/Library/Caches/deno/deps"
TypeScript compiler cache: "/Users/mark/Library/Caches/deno/gen"
# help 를 이용해서 SUBCOMMAND info 사용법 확인
➜ deno help info
Without any additional arguments, 'deno info' shows:
DENO_DIR: Directory containing Deno-managed files.
Remote modules cache: Subdirectory containing downloaded remote modules.
TypeScript compiler cache: Subdirectory containing TS compiler output.
"use strict";
console.log("Welcome to Deno 🦕");
//# sourceMappingURL=file:///Users/mark/Library/Caches/deno/gen/https/deno.land/std/examples/welcome.ts.js.map
~/FastCampus/deno2021
➜ deno cache https://deno.land/std/examples/welcome.ts
Download https://deno.land/std/examples/welcome.ts
Warning Implicitly using master branch https://deno.land/std/examples/welcome.ts
Compile https://deno.land/std/examples/welcome.ts
~/FastCampus/deno2021
➜ deno cache https://deno.land/std/examples/welcome.ts
~/FastCampus/deno2021
➜ deno cache -r https://deno.land/std/examples/welcome.ts
Download https://deno.land/std/examples/welcome.ts
Warning Implicitly using master branch https://deno.land/std/examples/welcome.ts
Compile https://deno.land/std/examples/welcome.ts
➜ deno -r -c tsconfig.json welcome2.ts
[3/3] Compiling file:///Users/mark/deno/deno-is-coming/welcome2.ts
decorator1
Welcome to Deno 🦕
// .profile
export PATH="$HOME/.deno/bin:$PATH"
export DENO_DIR="$HOME/.deno"
➜ DENO_DIR=`pwd`/.deno deno -c tsconfig.json welcome2.ts
[2/2] Compiling file:///Users/mark/deno/deno-is-coming/welcome2.ts
decorator1
Welcome to Deno 🦕
➜ deno help bundle
deno-bundle
Output a single JavaScript file with all dependencies.
deno bundle https://deno.land/std/examples/colors.ts colors.bundle.js
If no output file is given, the output is written to standard output:
deno bundle https://deno.land/std/examples/colors.ts
USAGE:
deno bundle [OPTIONS] <source_file> [out_file]
OPTIONS:
--cert <FILE> Load certificate authority from PEM encoded file
-c, --config <FILE> Load tsconfig.json configuration file
-h, --help Prints help information
--importmap <FILE> UNSTABLE: Load import map file
-L, --log-level <log-level> Set log level [possible values: debug, info]
-q, --quiet Suppress diagnostic output
--unstable Enable unstable APIs
ARGS:
<source_file>
<out_file>
~/FastCampus/deno2021
➜ deno bundle welcome.ts welcome.bundle.js
Bundling file:///Users/mark/FastCampus/deno2021/welcome.ts
Emitting bundle to "welcome.bundle.js"
2.36 KB emitted.
~/FastCampus/deno2021
➜ deno run welcome.bundle.js
Hello Deno
~/FastCampus/deno2021
➜ deno bundle https://deno.land/std/examples/welcome.ts welcome.bundle.js
Bundling https://deno.land/std/examples/welcome.ts
Emitting bundle to "welcome.bundle.js"
2.37 KB emitted.
~/FastCampus/deno2021
➜ deno run welcome.bundle.js
Welcome to Deno 🦕
import * as color from "https://deno.land/std@0.103.0/fmt/colors.ts";
console.log(color.yellow("Hello Deno"));
~/FastCampus/deno2021 via
➜ deno run welcome-with-color.ts
Download https://raw.githubusercontent.com/denoland/deno/master/std/fmt/colors.ts
Compile file:///Users/mark/FastCampus/deno2021/welcome-with-color.ts
Hello Deno
~/FastCampus/deno2021
➜ deno bundle welcome-with-color.ts welcome-with-color.bundle.js
Bundling file:///Users/mark/FastCampus/deno2021/welcome-with-color.ts
Emitting bundle to "welcome-with-color.bundle.js"
9.42 KB emitted.
~/FastCampus/deno2021
➜ deno run welcome-with-color.bundle.js
Hello Deno
➜ deno help doc
deno-doc
Show documentation for a module.
Output documentation to standard output:
deno doc ./path/to/module.ts
Output documentation in JSON format:
deno doc --json ./path/to/module.ts
Target a specific symbol:
deno doc ./path/to/module.ts MyClass.someField
Show documentation for runtime built-ins:
deno doc
deno doc --builtin Deno.Listener
USAGE:
deno doc [OPTIONS] [ARGS]
OPTIONS:
-h, --help Prints help information
--json Output documentation in JSON format.
-L, --log-level <log-level> Set log level [possible values: debug, info]
-q, --quiet Suppress diagnostic output
-r, --reload=<CACHE_BLACKLIST> Reload source code cache (recompile TypeScript)
--unstable Enable unstable APIs
ARGS:
<source_file>
<filter> Dot separated path to symbol.
➜ deno doc https://deno.land/std@0.103.0/fmt/colors.ts
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:281:0
function bgBlack(str: string): string
Set background color to black.
@param str text to make its background black
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:313:0
function bgBlue(str: string): string
Set background color to blue.
@param str text to make its background blue
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:345:0
function bgBrightBlack(str: string): string
Set background color to bright black.
@param str text to make its background bright-black
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:377:0
function bgBrightBlue(str: string): string
Set background color to bright blue.
@param str text to make its background bright-blue
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:393:0
function bgBrightCyan(str: string): string
Set background color to bright cyan.
@param str text to make its background bright-cyan
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:361:0
function bgBrightGreen(str: string): string
Set background color to bright green.
@param str text to make its background bright-green
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:385:0
function bgBrightMagenta(str: string): string
Set background color to bright magenta.
@param str text to make its background bright-magenta
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:353:0
function bgBrightRed(str: string): string
Set background color to bright red.
@param str text to make its background bright-red
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:401:0
function bgBrightWhite(str: string): string
Set background color to bright white.
@param str text to make its background bright-white
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:369:0
function bgBrightYellow(str: string): string
Set background color to bright yellow.
@param str text to make its background bright-yellow
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:329:0
function bgCyan(str: string): string
Set background color to cyan.
@param str text to make its background cyan
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:297:0
function bgGreen(str: string): string
Set background color to green.
@param str text to make its background green
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:321:0
function bgMagenta(str: string): string
Set background color to magenta.
@param str text to make its background magenta
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:289:0
function bgRed(str: string): string
Set background color to red.
@param str text to make its background red
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:486:0
function bgRgb24(str: string, color: number | Rgb): string
Set background color using 24bit rgb.
`color` can be a number in range `0x000000` to `0xffffff` or
an `Rgb`.
To produce the color magenta:
bgRgb24("foo", 0xff00ff);
bgRgb24("foo", {r: 255, g: 0, b: 255});
@param str text color to apply 24bit rgb to
@param color code
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:433:0
function bgRgb8(str: string, color: number): string
Set background color using paletted 8bit colors.
https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
@param str text color to apply paletted 8bit background colors to
@param color code
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:337:0
function bgWhite(str: string): string
Set background color to white.
@param str text to make its background white
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:305:0
function bgYellow(str: string): string
Set background color to yellow.
@param str text to make its background yellow
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:145:0
function black(str: string): string
Set text color to black.
@param str text to make black
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:177:0
function blue(str: string): string
Set text color to blue.
@param str text to make blue
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:89:0
function bold(str: string): string
Make the text bold.
@param str text to make bold
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:217:0
function brightBlack(str: string): string
Set text color to bright black.
@param str text to make bright-black
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:249:0
function brightBlue(str: string): string
Set text color to bright blue.
@param str text to make bright-blue
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:265:0
function brightCyan(str: string): string
Set text color to bright cyan.
@param str text to make bright-cyan
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:233:0
function brightGreen(str: string): string
Set text color to bright green.
@param str text to make bright-green
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:257:0
function brightMagenta(str: string): string
Set text color to bright magenta.
@param str text to make bright-magenta
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:225:0
function brightRed(str: string): string
Set text color to bright red.
@param str text to make bright-red
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:273:0
function brightWhite(str: string): string
Set text color to bright white.
@param str text to make bright-white
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:241:0
function brightYellow(str: string): string
Set text color to bright yellow.
@param str text to make bright-yellow
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:193:0
function cyan(str: string): string
Set text color to cyan.
@param str text to make cyan
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:97:0
function dim(str: string): string
The text emits only a small amount of light.
@param str text to dim
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:49:0
function getColorEnabled(): boolean
Get whether text color change is enabled or disabled.
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:209:0
function gray(str: string): string
Set text color to gray.
@param str text to make gray
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:161:0
function green(str: string): string
Set text color to green.
@param str text to make green
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:129:0
function hidden(str: string): string
Make the text hidden.
@param str text to hide
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:121:0
function inverse(str: string): string
Invert background color and text color.
@param str text to invert its color
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:105:0
function italic(str: string): string
Make the text italic.
@param str text to make italic
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:185:0
function magenta(str: string): string
Set text color to magenta.
@param str text to make magenta
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:153:0
function red(str: string): string
Set text color to red.
@param str text to make red
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:81:0
function reset(str: string): string
Reset the text modified
@param str text to reset
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:449:0
function rgb24(str: string, color: number | Rgb): string
Set text color using 24bit rgb.
`color` can be a number in range `0x000000` to `0xffffff` or
an `Rgb`.
To produce the color magenta:
rgb24("foo", 0xff00ff);
rgb24("foo", {r: 255, g: 0, b: 255});
@param str text color to apply 24bit rgb to
@param color code
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:423:0
function rgb8(str: string, color: number): string
Set text color using paletted 8bit colors.
https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
@param str text color to apply paletted 8bit colors to
@param color code
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:40:0
function setColorEnabled(value: boolean): void
Set changing text color to enabled or disabled
@param value
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:137:0
function strikethrough(str: string): string
Put horizontal line through the center of the text.
@param str text to strike through
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:524:0
function stripColor(string: string): string
Remove ANSI escape codes from the string.
@param string to remove ANSI escape codes from
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:113:0
function underline(str: string): string
Make the text underline.
@param str text to underline
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:201:0
function white(str: string): string
Set text color to white.
@param str text to make white
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:169:0
function yellow(str: string): string
Set text color to yellow.
@param str text to make yellow
➜ deno doc --json https://deno.land/std@0.103.0/fmt/colors.ts
[
{
"kind": "function",
"name": "setColorEnabled",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 40,
"col": 0
},
"jsDoc": "Set changing text color to enabled or disabled\n@param value",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "value",
"optional": false,
"tsType": {
"repr": "boolean",
"kind": "keyword",
"keyword": "boolean"
}
}
],
"returnType": {
"repr": "void",
"kind": "keyword",
"keyword": "void"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "getColorEnabled",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 49,
"col": 0
},
"jsDoc": "Get whether text color change is enabled or disabled.",
"functionDef": {
"params": [],
"returnType": {
"repr": "boolean",
"kind": "keyword",
"keyword": "boolean"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "reset",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 81,
"col": 0
},
"jsDoc": "Reset the text modified\n@param str text to reset",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bold",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 89,
"col": 0
},
"jsDoc": "Make the text bold.\n@param str text to make bold",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "dim",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 97,
"col": 0
},
"jsDoc": "The text emits only a small amount of light.\n@param str text to dim",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "italic",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 105,
"col": 0
},
"jsDoc": "Make the text italic.\n@param str text to make italic",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "underline",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 113,
"col": 0
},
"jsDoc": "Make the text underline.\n@param str text to underline",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "inverse",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 121,
"col": 0
},
"jsDoc": "Invert background color and text color.\n@param str text to invert its color",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "hidden",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 129,
"col": 0
},
"jsDoc": "Make the text hidden.\n@param str text to hide",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "strikethrough",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 137,
"col": 0
},
"jsDoc": "Put horizontal line through the center of the text.\n@param str text to strike through",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "black",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 145,
"col": 0
},
"jsDoc": "Set text color to black.\n@param str text to make black",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "red",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 153,
"col": 0
},
"jsDoc": "Set text color to red.\n@param str text to make red",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "green",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 161,
"col": 0
},
"jsDoc": "Set text color to green.\n@param str text to make green",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "yellow",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 169,
"col": 0
},
"jsDoc": "Set text color to yellow.\n@param str text to make yellow",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "blue",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 177,
"col": 0
},
"jsDoc": "Set text color to blue.\n@param str text to make blue",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "magenta",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 185,
"col": 0
},
"jsDoc": "Set text color to magenta.\n@param str text to make magenta",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "cyan",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 193,
"col": 0
},
"jsDoc": "Set text color to cyan.\n@param str text to make cyan",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "white",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 201,
"col": 0
},
"jsDoc": "Set text color to white.\n@param str text to make white",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "gray",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 209,
"col": 0
},
"jsDoc": "Set text color to gray.\n@param str text to make gray",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightBlack",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 217,
"col": 0
},
"jsDoc": "Set text color to bright black.\n@param str text to make bright-black",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightRed",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 225,
"col": 0
},
"jsDoc": "Set text color to bright red.\n@param str text to make bright-red",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightGreen",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 233,
"col": 0
},
"jsDoc": "Set text color to bright green.\n@param str text to make bright-green",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightYellow",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 241,
"col": 0
},
"jsDoc": "Set text color to bright yellow.\n@param str text to make bright-yellow",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightBlue",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 249,
"col": 0
},
"jsDoc": "Set text color to bright blue.\n@param str text to make bright-blue",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightMagenta",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 257,
"col": 0
},
"jsDoc": "Set text color to bright magenta.\n@param str text to make bright-magenta",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightCyan",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 265,
"col": 0
},
"jsDoc": "Set text color to bright cyan.\n@param str text to make bright-cyan",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "brightWhite",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 273,
"col": 0
},
"jsDoc": "Set text color to bright white.\n@param str text to make bright-white",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBlack",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 281,
"col": 0
},
"jsDoc": "Set background color to black.\n@param str text to make its background black",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgRed",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 289,
"col": 0
},
"jsDoc": "Set background color to red.\n@param str text to make its background red",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgGreen",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 297,
"col": 0
},
"jsDoc": "Set background color to green.\n@param str text to make its background green",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgYellow",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 305,
"col": 0
},
"jsDoc": "Set background color to yellow.\n@param str text to make its background yellow",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBlue",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 313,
"col": 0
},
"jsDoc": "Set background color to blue.\n@param str text to make its background blue",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgMagenta",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 321,
"col": 0
},
"jsDoc": "Set background color to magenta.\n@param str text to make its background magenta",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgCyan",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 329,
"col": 0
},
"jsDoc": "Set background color to cyan.\n@param str text to make its background cyan",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgWhite",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 337,
"col": 0
},
"jsDoc": "Set background color to white.\n@param str text to make its background white",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightBlack",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 345,
"col": 0
},
"jsDoc": "Set background color to bright black.\n@param str text to make its background bright-black",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightRed",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 353,
"col": 0
},
"jsDoc": "Set background color to bright red.\n@param str text to make its background bright-red",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightGreen",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 361,
"col": 0
},
"jsDoc": "Set background color to bright green.\n@param str text to make its background bright-green",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightYellow",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 369,
"col": 0
},
"jsDoc": "Set background color to bright yellow.\n@param str text to make its background bright-yellow",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightBlue",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 377,
"col": 0
},
"jsDoc": "Set background color to bright blue.\n@param str text to make its background bright-blue",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightMagenta",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 385,
"col": 0
},
"jsDoc": "Set background color to bright magenta.\n@param str text to make its background bright-magenta",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightCyan",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 393,
"col": 0
},
"jsDoc": "Set background color to bright cyan.\n@param str text to make its background bright-cyan",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgBrightWhite",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 401,
"col": 0
},
"jsDoc": "Set background color to bright white.\n@param str text to make its background bright-white",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "rgb8",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 423,
"col": 0
},
"jsDoc": "Set text color using paletted 8bit colors.\nhttps://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n@param str text color to apply paletted 8bit colors to\n@param color code",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
},
{
"kind": "identifier",
"name": "color",
"optional": false,
"tsType": {
"repr": "number",
"kind": "keyword",
"keyword": "number"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgRgb8",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 433,
"col": 0
},
"jsDoc": "Set background color using paletted 8bit colors.\nhttps://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n@param str text color to apply paletted 8bit background colors to\n@param color code",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
},
{
"kind": "identifier",
"name": "color",
"optional": false,
"tsType": {
"repr": "number",
"kind": "keyword",
"keyword": "number"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "rgb24",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 449,
"col": 0
},
"jsDoc": "Set text color using 24bit rgb.\n`color` can be a number in range `0x000000` to `0xffffff` or\nan `Rgb`.\n\nTo produce the color magenta:\n\n rgb24(\"foo\", 0xff00ff);\n rgb24(\"foo\", {r: 255, g: 0, b: 255});\n@param str text color to apply 24bit rgb to\n@param color code",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
},
{
"kind": "identifier",
"name": "color",
"optional": false,
"tsType": {
"repr": "",
"kind": "union",
"union": [
{
"repr": "number",
"kind": "keyword",
"keyword": "number"
},
{
"repr": "Rgb",
"kind": "typeRef",
"typeRef": {
"typeParams": null,
"typeName": "Rgb"
}
}
]
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "bgRgb24",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 486,
"col": 0
},
"jsDoc": "Set background color using 24bit rgb.\n`color` can be a number in range `0x000000` to `0xffffff` or\nan `Rgb`.\n\nTo produce the color magenta:\n\n bgRgb24(\"foo\", 0xff00ff);\n bgRgb24(\"foo\", {r: 255, g: 0, b: 255});\n@param str text color to apply 24bit rgb to\n@param color code",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "str",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
},
{
"kind": "identifier",
"name": "color",
"optional": false,
"tsType": {
"repr": "",
"kind": "union",
"union": [
{
"repr": "number",
"kind": "keyword",
"keyword": "number"
},
{
"repr": "Rgb",
"kind": "typeRef",
"typeRef": {
"typeParams": null,
"typeName": "Rgb"
}
}
]
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
},
{
"kind": "function",
"name": "stripColor",
"location": {
"filename": "https://deno.land/std@0.103.0/fmt/colors.ts",
"line": 524,
"col": 0
},
"jsDoc": "Remove ANSI escape codes from the string.\n@param string to remove ANSI escape codes from",
"functionDef": {
"params": [
{
"kind": "identifier",
"name": "string",
"optional": false,
"tsType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
}
}
],
"returnType": {
"repr": "string",
"kind": "keyword",
"keyword": "string"
},
"isAsync": false,
"isGenerator": false,
"typeParams": []
}
}
]
➜ deno doc https://deno.land/std@0.103.0/fmt/colors.ts yellow
Defined in https://deno.land/std@0.103.0/fmt/colors.ts:169:0
function yellow(str: string): string
Set text color to yellow.
@param str text to make yellow
➜ deno doc
Defined in lib.deno.d.ts:6036:0
function addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions | undefined): void
Registers an event listener in the global scope, which will be called
synchronously whenever the event `type` is dispatched.
addEventListener('unload', () => { console.log('All finished!'); });
...
dispatchEvent(new Event('unload'));
Defined in lib.deno.d.ts:6008:0
function alert(message?: string): void
Shows the given message and waits for the enter key pressed.
If the stdin is not interactive, it does nothing.
@param message
Defined in lib.deno.d.ts:2760:0
function atob(s: string): string
Decodes a string of data which has been encoded using base-64 encoding.
console.log(atob("aGVsbG8gd29ybGQ=")); // outputs 'hello world'
Defined in lib.deno.d.ts:2766:0
function btoa(s: string): string
Creates a base-64 ASCII encoded string from the input string.
console.log(btoa("hello world")); // outputs "aGVsbG8gd29ybGQ="
Defined in lib.deno.d.ts:5731:0
function clearInterval(id?: number): void
Cancels a timed, repeating action which was previously started by a call
to `setInterval()`
const id = setInterval(() => {console.log('hello');}, 500);
...
clearInterval(id);
Defined in lib.deno.d.ts:5739:0
function clearTimeout(id?: number): void
Cancels a scheduled action initiated by `setTimeout()`
const id = setTimeout(() => {console.log('hello');}, 500);
...
clearTimeout(id);
Defined in lib.deno.d.ts:6016:0
function confirm(message?: string): boolean
Shows the given message and waits for the answer. Returns the user's answer as boolean.
Only `y` and `Y` are considered as true.
If the stdin is not interactive, it returns false.
@param message
Defined in lib.deno.d.ts:5762:0
function dispatchEvent(event: Event): boolean
Dispatches an event in the global scope, synchronously invoking any
registered event listeners for this event in the appropriate order. Returns
false if event is cancelable and at least one of the event handlers which
handled this event called Event.preventDefault(). Otherwise it returns true.
dispatchEvent(new Event('unload'));
Defined in lib.deno.d.ts:3762:0
function fetch(input: Request | URL | string, init?: RequestInit): Promise<Response>
Fetch a resource from the network. It returns a Promise that resolves to the
Response to that request, whether it is successful or not.
const response = await fetch("http://my.json.host/data.json");
console.log(response.status); // e.g. 200
console.log(response.statusText); // e.g. "OK"
const jsonData = await response.json();
Defined in lib.deno.d.ts:6027:0
function prompt(message?: string, defaultValue?: string): string | null
Shows the given message and waits for the user's input. Returns the user's input as string.
If the default value is given and the user inputs the empty string, then it returns the given
default value.
If the default value is not given and the user inputs the empty string, it returns null.
If the stdin is not interactive, it returns null.
@param message
@param defaultValue
Defined in lib.deno.d.ts:5753:0
function queueMicrotask(func: VoidFunction): void
A microtask is a short function which is executed after the function or
module which created it exits and only if the JavaScript execution stack is
empty, but before returning control to the event loop being used to drive the
script's execution environment. This event loop may be either the main event
loop or the event loop driving a web worker.
queueMicrotask(() => { console.log('This event loop stack is complete'); });
Defined in lib.deno.d.ts:6048:0
function removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined): void
Remove a previously registered event listener from the global scope
const lstnr = () => { console.log('hello'); };
addEventListener('load', lstnr);
removeEventListener('load', lstnr);
Defined in lib.deno.d.ts:5715:0
function setInterval(cb: (...args: any[]) => void, delay?: number, ...args: any[]): number
Repeatedly calls a function , with a fixed time delay between each call.
// Outputs 'hello' to the console every 500ms
setInterval(() => { console.log('hello'); }, 500);
Defined in lib.deno.d.ts:5701:0
function setTimeout(cb: (...args: any[]) => void, delay?: number, ...args: any[]): number
Sets a timer which executes a function once after the timer expires. Returns
an id which may be used to cancel the timeout.
setTimeout(() => { console.log('hello'); }, 500);
Defined in lib.deno.d.ts:2868:0
var AbortSignal: { prototype: AbortSignal; }
Defined in lib.deno.d.ts:5250:0
var BroadcastChannel: { prototype: BroadcastChannel; }
Defined in lib.deno.d.ts:5119:0
var CryptoKey: { prototype: CryptoKey; }
Defined in lib.deno.d.ts:5130:0
var CryptoKeyPair: { prototype: CryptoKeyPair; }
Defined in lib.deno.d.ts:2925:0
var FileReader: { prototype: FileReader; DONE: number; EMPTY: number; LOADING: number; }
Defined in lib.deno.d.ts:3061:0
var ReadableByteStreamController: { prototype: ReadableByteStreamController; }
Defined in lib.deno.d.ts:3124:0
var ReadableStream: { prototype: ReadableStream; }
Defined in lib.deno.d.ts:3048:0
var ReadableStreamDefaultController: { prototype: ReadableStreamDefaultController; }
Defined in lib.deno.d.ts:2990:0
var ReadableStreamDefaultReader: { prototype: ReadableStreamDefaultReader; }
Defined in lib.deno.d.ts:3001:0
var ReadableStreamReader: { prototype: ReadableStreamReader; }
Defined in lib.deno.d.ts:5050:0
var Storage: { prototype: Storage; }
Defined in lib.deno.d.ts:5194:0
var SubtleCrypto: { prototype: SubtleCrypto; }
Defined in lib.deno.d.ts:3205:0
var TransformStream: { prototype: TransformStream; }
Defined in lib.deno.d.ts:3165:0
var WritableStream: { prototype: WritableStream; }
Defined in lib.deno.d.ts:3195:0
var WritableStreamDefaultWriter: { prototype: WritableStreamDefaultWriter; }
Defined in lib.deno.d.ts:5776:0
var console: Console
Defined in lib.deno.d.ts:5060:0
var crypto: Crypto
Defined in lib.deno.d.ts:5993:0
var localStorage: Storage
Defined in lib.deno.d.ts:6124:0
var location: Location
Defined in lib.deno.d.ts:6001:0
var navigator: Navigator
Defined in lib.deno.d.ts:5991:0
var onload: ((this: Window, ev: Event) => any) | null
Defined in lib.deno.d.ts:5992:0
var onunload: ((this: Window, ev: Event) => any) | null
Defined in lib.deno.d.ts:5886:0
var performance: Performance
Defined in lib.deno.d.ts:5990:0
var self: Window & typeof globalThis
Defined in lib.deno.d.ts:5994:0
var sessionStorage: Storage
Defined in lib.deno.d.ts:5989:0
var window: Window & typeof globalThis
Defined in lib.deno.d.ts:2827:0
class AbortController
A controller object that allows you to abort one or more DOM requests as and
when desired.
readonly signal: AbortSignal
Returns the AbortSignal object associated with this object.
abort(): void
Invoking this method will set this object's AbortSignal's aborted flag and
signal to any observers that the associated activity is to be aborted.
Defined in lib.deno.d.ts:2941:0
class Blob
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
constructor(blobParts?: BlobPart[], options?: BlobPropertyBag)
readonly size: number
readonly type: string
arrayBuffer(): Promise<ArrayBuffer>
slice(start?: number, end?: number, contentType?: string): Blob
stream(): ReadableStream<Uint8Array>
text(): Promise<string>
Defined in lib.deno.d.ts:3090:0
class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView>
constructor(options: { highWaterMark: number; })
highWaterMark: number
size(chunk: ArrayBufferView): number
Defined in lib.deno.d.ts:4912:0
class CloseEvent extends Event
constructor(type: string, eventInitDict?: CloseEventInit)
readonly code: number
Returns the WebSocket connection close code provided by the server.
readonly reason: string
Returns the WebSocket connection close reason provided by the server.
readonly wasClean: boolean
Returns true if the connection closed cleanly; false otherwise.
Defined in lib.deno.d.ts:3084:0
class CountQueuingStrategy implements QueuingStrategy
This Streams API interface provides a built-in byte length queuing strategy
that can be used when constructing streams.
constructor(options: { highWaterMark: number; })
highWaterMark: number
size(chunk: any): 1
Defined in lib.deno.d.ts:5946:0
class CustomEvent<T = any> extends Event
constructor(typeArg: string, eventInitDict?: CustomEventInit<T>)
readonly detail: T
Returns any custom data event was created with. Typically used for
synthetic events.
Defined in lib.deno.d.ts:2596:0
class DOMException extends Error
constructor(message?: string, name?: string)
readonly name: string
readonly message: string
readonly code: number
Defined in lib.deno.d.ts:5786:0
class ErrorEvent extends Event
constructor(type: string, eventInitDict?: ErrorEventInit)
readonly message: string
readonly filename: string
readonly lineno: number
readonly colno: number
readonly error: any
Defined in lib.deno.d.ts:2610:0
class Event
An event which takes place in the DOM.
constructor(type: string, eventInitDict?: EventInit)
readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if
event goes through its target's ancestors in reverse tree order, and
false otherwise.
cancelBubble: boolean
readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return
value does not always carry meaning, but true can indicate that part of the
operation during which event was dispatched, can be canceled by invoking
the preventDefault() method.
readonly composed: boolean
Returns true or false depending on how event was initialized. True if
event invokes listeners past a ShadowRoot node that is the root of its
target, and false otherwise.
readonly currentTarget: EventTarget | null
Returns the object whose event listener's callback is currently being
invoked.
readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate
cancellation, and false otherwise.
readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE,
AT_TARGET, and BUBBLING_PHASE.
readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false
otherwise.
readonly target: EventTarget | null
Returns the object to which event is dispatched (its target).
readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured
relative to the time origin.
readonly type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
readonly AT_TARGET: number
readonly BUBBLING_PHASE: number
readonly CAPTURING_PHASE: number
readonly NONE: number
static readonly AT_TARGET: number
static readonly BUBBLING_PHASE: number
static readonly CAPTURING_PHASE: number
static readonly NONE: number
composedPath(): EventTarget[]
Returns the invocation target objects of event's path (objects on which
listeners will be invoked), except for any nodes in shadow trees of which
the shadow root's mode is "closed" that are not reachable from event's
currentTarget.
preventDefault(): void
If invoked when the cancelable attribute value is true, and while
executing a listener for the event with passive set to false, signals to
the operation that caused event to be dispatched that it needs to be
canceled.
stopImmediatePropagation(): void
Invoking this method prevents event from reaching any registered event
listeners after the current one finishes running and, when dispatched in a
tree, also prevents event from reaching any other objects.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from
reaching any objects other than the current object.
Defined in lib.deno.d.ts:2676:0
class EventTarget
EventTarget is a DOM interface implemented by objects that can receive events
and may have listeners for them.
addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void
Appends an event listener for events whose type attribute value is type.
The callback argument sets the callback that will be invoked when the event
is dispatched.
The options argument sets listener-specific options. For compatibility this
can be a boolean, in which case the method behaves exactly as if the value
was specified as options's capture.
When set to true, options's capture prevents callback from being invoked
when the event's eventPhase attribute value is BUBBLING_PHASE. When false
(or not present), callback will not be invoked when event's eventPhase
attribute value is CAPTURING_PHASE. Either way, callback will be invoked if
event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not
cancel the event by invoking preventDefault(). This is used to enable
performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be
invoked once after which the event listener will be removed.
The event listener is appended to target's event listener list and is not
appended if it has the same type, callback, and capture.
dispatchEvent(event: Event): boolean
Dispatches a synthetic event event to target and returns true if either
event's cancelable attribute value is false or its preventDefault() method
was not invoked, and false otherwise.
removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void
Removes the event listener in target's event listener list with the same
type, callback, and options.
Defined in lib.deno.d.ts:2958:0
class File extends Blob
Provides information about files and allows JavaScript in a web page to
access their content.
constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag)
readonly lastModified: number
readonly name: string
Defined in lib.deno.d.ts:3353:0
class FormData implements DomIterable<string, FormDataEntryValue>
Provides a way to easily construct a set of key/value pairs representing
form fields and their values, which can then be easily sent using the
XMLHttpRequest.send() method. It uses the same format a form would use if the
encoding type were set to "multipart/form-data".
constructor()
append(name: string, value: string | Blob, fileName?: string): void
delete(name: string): void
get(name: string): FormDataEntryValue | null
getAll(name: string): FormDataEntryValue[]
has(name: string): boolean
set(name: string, value: string | Blob, fileName?: string): void
keys(): IterableIterator<string>
values(): IterableIterator<string>
entries(): IterableIterator<[string, FormDataEntryValue]>
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>
forEach(callback: (value: FormDataEntryValue, key: string, parent: this) => void, thisArg?: any): void
Defined in lib.deno.d.ts:3830:0
class GPU
requestAdapter(options?: GPURequestAdapterOptions): Promise<GPUAdapter | null>
Defined in lib.deno.d.ts:3843:0
class GPUAdapter
readonly name: string
readonly features: GPUSupportedFeatures
readonly limits: GPUSupportedLimits
readonly isSoftware: boolean
requestDevice(descriptor?: GPUDeviceDescriptor): Promise<GPUDevice>
Defined in lib.deno.d.ts:4183:0
class GPUBindGroup implements GPUObjectBase
label: string | null
Defined in lib.deno.d.ts:4114:0
class GPUBindGroupLayout implements GPUObjectBase
label: string | null
Defined in lib.deno.d.ts:3933:0
class GPUBuffer implements GPUObjectBase
label: string | null
mapAsync(mode: GPUMapModeFlags, offset?: number, size?: number): Promise<undefined>
getMappedRange(offset?: number, size?: number): ArrayBuffer
unmap(): undefined
destroy(): undefined
Defined in lib.deno.d.ts:3954:0
class GPUBufferUsage
static MAP_READ: 1
static MAP_WRITE: 2
static COPY_SRC: 4
static COPY_DST: 8
static INDEX: 16
static VERTEX: 32
static UNIFORM: 64
static STORAGE: 128
static INDIRECT: 256
static QUERY_RESOLVE: 512
Defined in lib.deno.d.ts:4321:0
class GPUColorWrite
static RED: 1
static GREEN: 2
static BLUE: 4
static ALPHA: 8
static ALL: 15
Defined in lib.deno.d.ts:4443:0
class GPUCommandBuffer implements GPUObjectBase
label: string | null
readonly executionTime: Promise<number>
Defined in lib.deno.d.ts:4451:0
class GPUCommandEncoder implements GPUObjectBase
label: string | null
beginRenderPass(descriptor: GPURenderPassDescriptor): GPURenderPassEncoder
beginComputePass(descriptor?: GPUComputePassDescriptor): GPUComputePassEncoder
copyBufferToBuffer(source: GPUBuffer, sourceOffset: number, destination: GPUBuffer, destinationOffset: number, size: number): undefined
copyBufferToTexture(source: GPUImageCopyBuffer, destination: GPUImageCopyTexture, copySize: GPUExtent3D): undefined
copyTextureToBuffer(source: GPUImageCopyTexture, destination: GPUImageCopyBuffer, copySize: GPUExtent3D): undefined
copyTextureToTexture(source: GPUImageCopyTexture, destination: GPUImageCopyTexture, copySize: GPUExtent3D): undefined
pushDebugGroup(groupLabel: string): undefined
popDebugGroup(): undefined
insertDebugMarker(markerLabel: string): undefined
writeTimestamp(querySet: GPUQuerySet, queryIndex: number): undefined
resolveQuerySet(querySet: GPUQuerySet, firstQuery: number, queryCount: number, destination: GPUBuffer, destinationOffset: number): undefined
finish(descriptor?: GPUCommandBufferDescriptor): GPUCommandBuffer
Defined in lib.deno.d.ts:4543:0
class GPUComputePassEncoder implements GPUObjectBase, GPUProgrammablePassEncoder
label: string | null
setBindGroup(index: number, bindGroup: GPUBindGroup, dynamicOffsets?: number[]): undefined
setBindGroup(index: number, bindGroup: GPUBindGroup, dynamicOffsetsData: Uint32Array, dynamicOffsetsDataStart: number, dynamicOffsetsDataLength: number): undefined
pushDebugGroup(groupLabel: string): undefined
popDebugGroup(): undefined
insertDebugMarker(markerLabel: string): undefined
setPipeline(pipeline: GPUComputePipeline): undefined
dispatch(x: number, y?: number, z?: number): undefined
dispatchIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined
beginPipelineStatisticsQuery(querySet: GPUQuerySet, queryIndex: number): undefined
endPipelineStatisticsQuery(): undefined
writeTimestamp(querySet: GPUQuerySet, queryIndex: number): undefined
endPass(): undefined
Defined in lib.deno.d.ts:4253:0
class GPUComputePipeline implements GPUObjectBase, GPUPipelineBase
label: string | null
getBindGroupLayout(index: number): GPUBindGroupLayout
Defined in lib.deno.d.ts:3881:0
class GPUDevice extends EventTarget implements GPUObjectBase
label: string | null
readonly lost: Promise<GPUDeviceLostInfo>
onuncapturederror: ((this: GPUDevice, ev: GPUUncapturedErrorEvent) => any) | null
readonly features: ReadonlyArray<GPUFeatureName>
readonly limits: Record<string, number>
readonly queue: GPUQueue
pushErrorScope(filter: GPUErrorFilter): undefined
popErrorScope(): Promise<GPUError | null>
destroy(): undefined
createBuffer(descriptor: GPUBufferDescriptor): GPUBuffer
createTexture(descriptor: GPUTextureDescriptor): GPUTexture
createSampler(descriptor?: GPUSamplerDescriptor): GPUSampler
createBindGroupLayout(descriptor: GPUBindGroupLayoutDescriptor): GPUBindGroupLayout
createPipelineLayout(descriptor: GPUPipelineLayoutDescriptor): GPUPipelineLayout
createBindGroup(descriptor: GPUBindGroupDescriptor): GPUBindGroup
createShaderModule(descriptor: GPUShaderModuleDescriptor): GPUShaderModule
createComputePipeline(descriptor: GPUComputePipelineDescriptor): GPUComputePipeline
createRenderPipeline(descriptor: GPURenderPipelineDescriptor): GPURenderPipeline
createComputePipelineAsync(descriptor: GPUComputePipelineDescriptor): Promise<GPUComputePipeline>
createRenderPipelineAsync(descriptor: GPURenderPipelineDescriptor): Promise<GPURenderPipeline>
createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): GPUCommandEncoder
createRenderBundleEncoder(descriptor: GPURenderBundleEncoderDescriptor): GPURenderBundleEncoder
createQuerySet(descriptor: GPUQuerySetDescriptor): GPUQuerySet
Defined in lib.deno.d.ts:3968:0
class GPUMapMode
static READ: 1
static WRITE: 2
Defined in lib.deno.d.ts:4851:0
class GPUOutOfMemoryError
constructor()
Defined in lib.deno.d.ts:4208:0
class GPUPipelineLayout implements GPUObjectBase
label: string | null
Defined in lib.deno.d.ts:4821:0
class GPUQuerySet implements GPUObjectBase
label: string | null
destroy(): undefined
Defined in lib.deno.d.ts:4798:0
class GPUQueue implements GPUObjectBase
label: string | null
submit(commandBuffers: GPUCommandBuffer[]): undefined
onSubmittedWorkDone(): Promise<undefined>
writeBuffer(buffer: GPUBuffer, bufferOffset: number, data: BufferSource, dataOffset?: number, size?: number): undefined
writeTexture(destination: GPUImageCopyTexture, data: BufferSource, dataLayout: GPUImageDataLayout, size: GPUExtent3D): undefined
Defined in lib.deno.d.ts:4732:0
class GPURenderBundle implements GPUObjectBase
label: string | null
Defined in lib.deno.d.ts:4738:0
class GPURenderBundleEncoder implements GPUObjectBase, GPUProgrammablePassEncoder, GPURenderEncoderBase
label: string | null
draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): undefined
drawIndexed(indexCount: number, instanceCount?: number, firstIndex?: number, baseVertex?: number, firstInstance?: number): undefined
drawIndexedIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined
drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined
insertDebugMarker(markerLabel: string): undefined
popDebugGroup(): undefined
pushDebugGroup(groupLabel: string): undefined
setBindGroup(index: number, bindGroup: GPUBindGroup, dynamicOffsets?: number[]): undefined
setBindGroup(index: number, bindGroup: GPUBindGroup, dynamicOffsetsData: Uint32Array, dynamicOffsetsDataStart: number, dynamicOffsetsDataLength: number): undefined
setIndexBuffer(buffer: GPUBuffer, indexFormat: GPUIndexFormat, offset?: number, size?: number): undefined
setPipeline(pipeline: GPURenderPipeline): undefined
setVertexBuffer(slot: number, buffer: GPUBuffer, offset?: number, size?: number): undefined
finish(descriptor?: GPURenderBundleDescriptor): GPURenderBundle
Defined in lib.deno.d.ts:4618:0
class GPURenderPassEncoder implements GPUObjectBase, GPUProgrammablePassEncoder, GPURenderEncoderBase
label: string | null
setBindGroup(index: number, bindGroup: GPUBindGroup, dynamicOffsets?: number[]): undefined
setBindGroup(index: number, bindGroup: GPUBindGroup, dynamicOffsetsData: Uint32Array, dynamicOffsetsDataStart: number, dynamicOffsetsDataLength: number): undefined
pushDebugGroup(groupLabel: string): undefined
popDebugGroup(): undefined
insertDebugMarker(markerLabel: string): undefined
setPipeline(pipeline: GPURenderPipeline): undefined
setIndexBuffer(buffer: GPUBuffer, indexFormat: GPUIndexFormat, offset?: number, size?: number): undefined
setVertexBuffer(slot: number, buffer: GPUBuffer, offset?: number, size?: number): undefined
draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): undefined
drawIndexed(indexCount: number, instanceCount?: number, firstIndex?: number, baseVertex?: number, firstInstance?: number): undefined
drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined
drawIndexedIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined
setViewport(x: number, y: number, width: number, height: number, minDepth: number, maxDepth: number): undefined
setScissorRect(x: number, y: number, width: number, height: number): undefined
setBlendConstant(color: GPUColor): undefined
setStencilReference(reference: number): undefined
beginOcclusionQuery(queryIndex: number): undefined
endOcclusionQuery(): undefined
beginPipelineStatisticsQuery(querySet: GPUQuerySet, queryIndex: number): undefined
endPipelineStatisticsQuery(): undefined
writeTimestamp(querySet: GPUQuerySet, queryIndex: number): undefined
executeBundles(bundles: GPURenderBundle[]): undefined
endPass(): undefined
Defined in lib.deno.d.ts:4264:0
class GPURenderPipeline implements GPUObjectBase, GPUPipelineBase
label: string | null
getBindGroupLayout(index: number): GPUBindGroupLayout
Defined in lib.deno.d.ts:4083:0
class GPUSampler implements GPUObjectBase
label: string | null
Defined in lib.deno.d.ts:4229:0
class GPUShaderModule implements GPUObjectBase
label: string | null
compilationInfo(): Promise<GPUCompilationInfo>
Defined in lib.deno.d.ts:4133:0
class GPUShaderStage
static VERTEX: 1
static FRAGMENT: 2
static COMPUTE: 4
Defined in lib.deno.d.ts:3810:0
class GPUSupportedFeatures
size: number
forEach(callbackfn: (value: GPUFeatureName, value2: GPUFeatureName, set: Set<GPUFeatureName>) => void, thisArg?: any): void
has(value: GPUFeatureName): boolean
[
Symbol
.iterator
](): IterableIterator<GPUFeatureName>
entries(): IterableIterator<[GPUFeatureName, GPUFeatureName]>
keys(): IterableIterator<GPUFeatureName>
values(): IterableIterator<GPUFeatureName>
Defined in lib.deno.d.ts:3784:0
class GPUSupportedLimits
maxTextureDimension1D?: number
maxTextureDimension2D?: number
maxTextureDimension3D?: number
maxTextureArrayLayers?: number
maxBindGroups?: number
maxDynamicUniformBuffersPerPipelineLayout?: number
maxDynamicStorageBuffersPerPipelineLayout?: number
maxSampledTexturesPerShaderStage?: number
maxSamplersPerShaderStage?: number
maxStorageBuffersPerShaderStage?: number
maxStorageTexturesPerShaderStage?: number
maxUniformBuffersPerShaderStage?: number
maxUniformBufferBindingSize?: number
maxStorageBufferBindingSize?: number
minUniformBufferOffsetAlignment?: number
minStorageBufferOffsetAlignment?: number
maxVertexBuffers?: number
maxVertexAttributes?: number
maxVertexBufferArrayStride?: number
maxInterStageShaderComponents?: number
maxComputeWorkgroupStorageSize?: number
maxComputeWorkgroupInvocations?: number
maxComputePerDimensionDispatchSize?: number
Defined in lib.deno.d.ts:3973:0
class GPUTexture implements GPUObjectBase
label: string | null
createView(descriptor?: GPUTextureViewDescriptor): GPUTextureView
destroy(): undefined
Defined in lib.deno.d.ts:3992:0
class GPUTextureUsage
static COPY_SRC: 1
static COPY_DST: 2
static SAMPLED: 4
static STORAGE: 8
static RENDER_ATTACHMENT: 16
Defined in lib.deno.d.ts:4000:0
class GPUTextureView implements GPUObjectBase
label: string | null
Defined in lib.deno.d.ts:4862:0
class GPUUncapturedErrorEvent extends Event
constructor(type: string, gpuUncapturedErrorEventInitDict: GPUUncapturedErrorEventInit)
readonly error: GPUError
Defined in lib.deno.d.ts:4855:0
class GPUValidationError
constructor(message: string)
readonly message: string
Defined in lib.deno.d.ts:3424:0
class Headers implements DomIterable<string, string>
constructor(init?: HeadersInit)
append(name: string, value: string): void
Appends a new value onto an existing header inside a `Headers` object, or
adds the header if it does not already exist.
delete(name: string): void
Deletes a header from a `Headers` object.
entries(): IterableIterator<[string, string]>
Returns an iterator allowing to go through all key/value pairs
contained in this Headers object. The both the key and value of each pairs
are ByteString objects.
get(name: string): string | null
Returns a `ByteString` sequence of all the values of a header within a
`Headers` object with a given name.
has(name: string): boolean
Returns a boolean stating whether a `Headers` object contains a certain
header.
keys(): IterableIterator<string>
Returns an iterator allowing to go through all keys contained in
this Headers object. The keys are ByteString objects.
set(name: string, value: string): void
Sets a new value for an existing header inside a Headers object, or adds
the header if it does not already exist.
values(): IterableIterator<string>
Returns an iterator allowing to go through all values contained in
this Headers object. The values are ByteString objects.
forEach(callbackfn: (value: string, key: string, parent: this) => void, thisArg?: any): void
[Symbol.iterator](): IterableIterator<[string, string]>
The Symbol.iterator well-known symbol specifies the default
iterator for this Headers object
Defined in lib.deno.d.ts:6059:0
class Location
The location (URL) of the object it is linked to. Changes done on it are
reflected on the object it relates to. Accessible via
`globalThis.location`.
constructor()
readonly ancestorOrigins: DOMStringList
Returns a DOMStringList object listing the origins of the ancestor
browsing contexts, from the parent browsing context to the top-level
browsing context.
Always empty in Deno.
hash: string
Returns the Location object's URL's fragment (includes leading "#" if
non-empty).
Cannot be set in Deno.
host: string
Returns the Location object's URL's host and port (if different from the
default port for the scheme).
Cannot be set in Deno.
hostname: string
Returns the Location object's URL's host.
Cannot be set in Deno.
href: string
Returns the Location object's URL.
Cannot be set in Deno.
readonly origin: string
Returns the Location object's URL's origin.
pathname: string
Returns the Location object's URL's path.
Cannot be set in Deno.
port: string
Returns the Location object's URL's port.
Cannot be set in Deno.
protocol: string
Returns the Location object's URL's scheme.
Cannot be set in Deno.
search: string
Returns the Location object's URL's query (includes leading "?" if
non-empty).
Cannot be set in Deno.
toString(): string
assign(url: string): void
Navigates to the given URL.
Cannot be set in Deno.
reload(): void
Reloads the current page.
Disabled in Deno.
reload(forcedReload: boolean): void
@deprecated
replace(url: string): void
Removes the current page from the session history and navigates to the
given URL.
Disabled in Deno.
Defined in lib.deno.d.ts:3271:0
class MessageChannel
The MessageChannel interface of the Channel Messaging API allows us to
create a new message channel and send data through it via its two MessagePort
properties.
constructor()
readonly port1: MessagePort
readonly port2: MessagePort
Defined in lib.deno.d.ts:3246:0
class MessageEvent<T = any> extends Event
constructor(type: string, eventInitDict?: MessageEventInit)
readonly data: T
Returns the data of the message.
readonly lastEventId: string
Returns the last event ID string, for server-sent events.
readonly ports: ReadonlyArray<MessagePort>
Returns transfered ports.
Defined in lib.deno.d.ts:3285:0
class MessagePort extends EventTarget
The MessagePort interface of the Channel Messaging API represents one of the
two ports of a MessageChannel, allowing messages to be sent from one port and
listening out for them arriving at the other.
onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null
onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null
close(): void
Disconnects the port, so that it is no longer active.
postMessage(message: any, transfer: Transferable[]): void
Posts a message through the channel. Objects listed in transfer are
transferred, not just cloned, meaning that they are no longer usable on the
sending side.
Throws a "DataCloneError" DOMException if transfer contains duplicate
objects or port, or if message could not be cloned.
postMessage(message: any, options?: PostMessageOptions): void
start(): void
Begins dispatching messages received on the port. This is implictly called
when assiging a value to `this.onmessage`.
addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void
removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void
Defined in lib.deno.d.ts:5996:0
class Navigator
constructor()
readonly gpu: GPU
Defined in lib.deno.d.ts:5844:0
class Performance
constructor()
clearMarks(markName?: string): void
Removes the stored timestamp with the associated name.
clearMeasures(measureName?: string): void
Removes stored timestamp with the associated name.
getEntries(): PerformanceEntryList
getEntriesByName(name: string, type?: string): PerformanceEntryList
getEntriesByType(type: string): PerformanceEntryList
mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark
Stores a timestamp with the associated name (a "mark").
measure(measureName: string, options?: PerformanceMeasureOptions): PerformanceMeasure
Stores the `DOMHighResTimeStamp` duration between two marks along with the
associated name (a "measure").
measure(measureName: string, startMark?: string, endMark?: string): PerformanceMeasure
Stores the `DOMHighResTimeStamp` duration between two marks along with the
associated name (a "measure").
now(): number
Returns a current time from Deno's start in milliseconds.
Use the permission flag `--allow-hrtime` return a precise value.
```ts
const t = performance.now();
console.log(`${t} ms since start!`);
```
Defined in lib.deno.d.ts:5915:0
class PerformanceEntry
Encapsulates a single performance metric that is part of the performance
timeline. A performance entry can be directly created by making a performance
mark or measure (for example by calling the `.mark()` method) at an explicit
point in an application.
readonly duration: number
readonly entryType: string
readonly name: string
readonly startTime: number
toJSON(): any
Defined in lib.deno.d.ts:5927:0
class PerformanceMark extends PerformanceEntry
`PerformanceMark` is an abstract interface for `PerformanceEntry` objects
with an entryType of `"mark"`. Entries of this type are created by calling
`performance.mark()` to add a named `DOMHighResTimeStamp` (the mark) to the
performance timeline.
constructor(name: string, options?: PerformanceMarkOptions)
readonly detail: any
readonly entryType: "mark"
Defined in lib.deno.d.ts:5937:0
class PerformanceMeasure extends PerformanceEntry
`PerformanceMeasure` is an abstract interface for `PerformanceEntry` objects
with an entryType of `"measure"`. Entries of this type are created by calling
`performance.measure()` to add a named `DOMHighResTimeStamp` (the measure)
between two marks to the performance timeline.
readonly detail: any
readonly entryType: "measure"
Defined in lib.deno.d.ts:2748:0
class ProgressEvent<T extends EventTarget = EventTarget> extends Event
Events measuring progress of an underlying process, like an HTTP request
(for an XMLHttpRequest, or the loading of the underlying resource of an
<img>, <audio>, <video>, <style> or <link>).
constructor(type: string, eventInitDict?: ProgressEventInit)
readonly lengthComputable: boolean
readonly loaded: number
readonly target: T | null
readonly total: number
Defined in lib.deno.d.ts:3581:0
class Request implements Body
This Fetch API interface represents a resource request.
constructor(input: RequestInfo, init?: RequestInit)
readonly cache: RequestCache
Returns the cache mode associated with request, which is a string
indicating how the request will interact with the browser's cache when
fetching.
readonly credentials: RequestCredentials
Returns the credentials mode associated with request, which is a string
indicating whether credentials will be sent with the request always, never,
or only when sent to a same-origin URL.
readonly destination: RequestDestination
Returns the kind of resource requested by request, e.g., "document" or "script".
readonly headers: Headers
Returns a Headers object consisting of the headers associated with request.
Note that headers added in the network layer by the user agent will not be
accounted for in this object, e.g., the "Host" header.
readonly integrity: string
Returns request's subresource integrity metadata, which is a cryptographic
hash of the resource being fetched. Its value consists of multiple hashes
separated by whitespace. [SRI]
readonly isHistoryNavigation: boolean
Returns a boolean indicating whether or not request is for a history
navigation (a.k.a. back-forward navigation).
readonly isReloadNavigation: boolean
Returns a boolean indicating whether or not request is for a reload
navigation.
readonly keepalive: boolean
Returns a boolean indicating whether or not request can outlive the global
in which it was created.
readonly method: string
Returns request's HTTP method, which is "GET" by default.
readonly mode: RequestMode
Returns the mode associated with request, which is a string indicating
whether the request will use CORS, or will be restricted to same-origin
URLs.
readonly redirect: RequestRedirect
Returns the redirect mode associated with request, which is a string
indicating how redirects for the request will be handled during fetching. A
request will follow redirects by default.
readonly referrer: string
Returns the referrer of request. Its value can be a same-origin URL if
explicitly set in init, the empty string to indicate no referrer, and
"about:client" when defaulting to the global's default. This is used during
fetching to determine the value of the `Referer` header of the request
being made.
readonly referrerPolicy: ReferrerPolicy
Returns the referrer policy associated with request. This is used during
fetching to compute the value of the request's referrer.
readonly signal: AbortSignal
Returns the signal associated with request, which is an AbortSignal object
indicating whether or not request has been aborted, and its abort event
handler.
readonly url: string
Returns the URL of request as a string.
readonly body: ReadableStream<Uint8Array> | null
A simple getter used to expose a `ReadableStream` of the body contents.
readonly bodyUsed: boolean
Stores a `Boolean` that declares whether the body has been used in a
response yet.
clone(): Request
arrayBuffer(): Promise<ArrayBuffer>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with an `ArrayBuffer`.
blob(): Promise<Blob>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with a `Blob`.
formData(): Promise<FormData>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with a `FormData` object.
json(): Promise<any>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with the result of parsing the body text as JSON.
text(): Promise<string>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with a `USVString` (text).
Defined in lib.deno.d.ts:3711:0
class Response implements Body
This Fetch API interface represents the response to a request.
constructor(body?: BodyInit | null, init?: ResponseInit)
readonly headers: Headers
readonly ok: boolean
readonly redirected: boolean
readonly status: number
readonly statusText: string
readonly trailer: Promise<Headers>
readonly type: ResponseType
readonly url: string
readonly body: ReadableStream<Uint8Array> | null
A simple getter used to expose a `ReadableStream` of the body contents.
readonly bodyUsed: boolean
Stores a `Boolean` that declares whether the body has been used in a
response yet.
static error(): Response
static redirect(url: string, status?: number): Response
clone(): Response
arrayBuffer(): Promise<ArrayBuffer>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with an `ArrayBuffer`.
blob(): Promise<Blob>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with a `Blob`.
formData(): Promise<FormData>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with a `FormData` object.
json(): Promise<any>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with the result of parsing the body text as JSON.
text(): Promise<string>
Takes a `Response` stream and reads it to completion. It returns a promise
that resolves with a `USVString` (text).
Defined in lib.deno.d.ts:2777:0
class TextDecoder
constructor(label?: string, options?: TextDecoderOptions)
readonly encoding: string
Returns encoding's name, lowercased.
readonly fatal: boolean
Returns `true` if error mode is "fatal", and `false` otherwise.
readonly ignoreBOM
Returns `true` if ignore BOM flag is set, and `false` otherwise.
decode(input?: BufferSource, options?: TextDecodeOptions): string
Returns the result of running encoding's decoder.
Defined in lib.deno.d.ts:2804:0
class TextDecoderStream
constructor(label?: string, options?: TextDecoderOptions)
readonly encoding: string
Returns encoding's name, lowercased.
readonly fatal: boolean
Returns `true` if error mode is "fatal", and `false` otherwise.
readonly ignoreBOM
Returns `true` if ignore BOM flag is set, and `false` otherwise.
readonly readable: ReadableStream<string>
readonly writable: WritableStream<BufferSource>
readonly [Symbol.toStringTag]: string
Defined in lib.deno.d.ts:2796:0
class TextEncoder
readonly encoding: "utf-8"
Returns "utf-8".
encode(input?: string): Uint8Array
Returns the result of running UTF-8's encoder.
encodeInto(input: string, dest: Uint8Array): TextEncoderEncodeIntoResult
Defined in lib.deno.d.ts:2817:0
class TextEncoderStream
readonly encoding: "utf-8"
Returns "utf-8".
readonly readable: ReadableStream<Uint8Array>
readonly writable: WritableStream<string>
readonly [Symbol.toStringTag]: string
Defined in lib.deno.d.ts:2568:0
class URL
The URL interface represents an object providing static methods used for creating object URLs.
constructor(url: string, base?: string | URL)
hash: string
host: string
hostname: string
href: string
readonly origin: string
password: string
pathname: string
port: string
protocol: string
search: string
readonly searchParams: URLSearchParams
username: string
static createObjectURL(blob: Blob): string
static revokeObjectURL(url: string): void
toString(): string
toJSON(): string
Defined in lib.deno.d.ts:2420:0
class URLSearchParams
constructor(init?: string[][] | Record<string, string> | string | URLSearchParams)
static toString(): string
append(name: string, value: string): void
Appends a specified key/value pair as a new search parameter.
```ts
let searchParams = new URLSearchParams();
searchParams.append('name', 'first');
searchParams.append('name', 'second');
```
delete(name: string): void
Deletes the given search parameter and its associated value,
from the list of all search parameters.
```ts
let searchParams = new URLSearchParams([['name', 'value']]);
searchParams.delete('name');
```
getAll(name: string): string[]
Returns all the values associated with a given search parameter
as an array.
```ts
searchParams.getAll('name');
```
get(name: string): string | null
Returns the first value associated to the given search parameter.
```ts
searchParams.get('name');
```
has(name: string): boolean
Returns a Boolean that indicates whether a parameter with the
specified name exists.
```ts
searchParams.has('name');
```
set(name: string, value: string): void
Sets the value associated with a given search parameter to the
given value. If there were several matching values, this method
deletes the others. If the search parameter doesn't exist, this
method creates it.
```ts
searchParams.set('name', 'value');
```
sort(): void
Sort all key/value pairs contained in this object in place and
return undefined. The sort order is according to Unicode code
points of the keys.
```ts
searchParams.sort();
```
forEach(callbackfn: (value: string, key: string, parent: this) => void, thisArg?: any): void
Calls a function for each element contained in this object in
place and return undefined. Optionally accepts an object to use
as this when executing callback as second argument.
```ts
const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
params.forEach((value, key, parent) => {
console.log(value, key, parent);
});
```
keys(): IterableIterator<string>
Returns an iterator allowing to go through all keys contained
in this object.
```ts
const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const key of params.keys()) {
console.log(key);
}
```
values(): IterableIterator<string>
Returns an iterator allowing to go through all values contained
in this object.
```ts
const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const value of params.values()) {
console.log(value);
}
```
entries(): IterableIterator<[string, string]>
Returns an iterator allowing to go through all key/value
pairs contained in this object.
```ts
const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const [key, value] of params.entries()) {
console.log(key, value);
}
```
[Symbol.iterator](): IterableIterator<[string, string]>
Returns an iterator allowing to go through all key/value
pairs contained in this object.
```ts
const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
for (const [key, value] of params) {
console.log(key, value);
}
```
toString(): string
Returns a query string suitable for use in a URL.
```ts
searchParams.toString();
```
Defined in lib.deno.d.ts:4936:0
class WebSocket extends EventTarget
Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
constructor(url: string, protocols?: string | string[])
static readonly CLOSED: number
static readonly CLOSING: number
static readonly CONNECTING: number
static readonly OPEN: number
binaryType: BinaryType
Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:
Can be set, to change how binary data is returned. The default is "blob".
readonly bufferedAmount: number
Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.
If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)
readonly extensions: string
Returns the extensions selected by the server, if any.
onclose: ((this: WebSocket, ev: CloseEvent) => any) | null
onerror: ((this: WebSocket, ev: Event | ErrorEvent) => any) | null
onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null
onopen: ((this: WebSocket, ev: Event) => any) | null
readonly protocol: string
Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
readonly readyState: number
Returns the state of the WebSocket object's connection. It can have the values described below.
readonly url: string
Returns the URL that was used to establish the WebSocket connection.
readonly CLOSED: number
readonly CLOSING: number
readonly CONNECTING: number
readonly OPEN: number
close(code?: number, reason?: string): void
Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void
Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void
removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void
Defined in lib.deno.d.ts:5969:0
class Window extends EventTarget
readonly window: Window & typeof globalThis
readonly self: Window & typeof globalThis
onload: ((this: Window, ev: Event) => any) | null
onunload: ((this: Window, ev: Event) => any) | null
close: () => void
readonly closed: boolean
alert: (message?: string) => void
confirm: (message?: string) => boolean
prompt: (message?: string, defaultValue?: string) => string | null
Deno: typeof Deno
Navigator: typeof Navigator
navigator: Navigator
Location: typeof Location
location: Location
localStorage: Storage
sessionStorage: Storage
new(): Window
Defined in lib.deno.d.ts:5809:0
class Worker extends EventTarget
constructor(specifier: string | URL, options?: WorkerOptions)
onerror?: (e: ErrorEvent) => void
onmessage?: (e: MessageEvent) => void
onmessageerror?: (e: MessageEvent) => void
postMessage(message: any, transfer: Transferable[]): void
postMessage(message: any, options?: PostMessageOptions): void
addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void
removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void
terminate(): void
Defined in lib.deno.d.ts:2391:0
interface Console
assert(condition?: boolean, ...data: any[]): void
clear(): void
count(label?: string): void
countReset(label?: string): void
debug(...data: any[]): void
dir(item?: any, options?: any): void
dirxml(...data: any[]): void
error(...data: any[]): void
group(...data: any[]): void
groupCollapsed(...data: any[]): void
groupEnd(): void
info(...data: any[]): void
log(...data: any[]): void
table(tabularData?: any, properties?: string[]): void
time(label?: string): void
timeEnd(label?: string): void
timeLog(label?: string, ...data: any[]): void
trace(...data: any[]): void
warn(...data: any[]): void
Defined in lib.deno.d.ts:5169:0
interface Crypto
subtle: SubtleCrypto
getRandomValues(array: T): T
randomUUID(): string
Defined in lib.deno.d.ts:5942:0
interface CustomEventInit<T = any> extends EventInit
detail?: T
Defined in lib.deno.d.ts:4187:0
interface GPUBindGroupDescriptor extends GPUObjectDescriptorBase
layout: GPUBindGroupLayout
entries: GPUBindGroupEntry[]
Defined in lib.deno.d.ts:4197:0
interface GPUBindGroupEntry
binding: number
resource: GPUBindingResource
Defined in lib.deno.d.ts:4118:0
interface GPUBindGroupLayoutDescriptor extends GPUObjectDescriptorBase
entries: GPUBindGroupLayoutEntry[]
Defined in lib.deno.d.ts:4122:0
interface GPUBindGroupLayoutEntry
binding: number
visibility: GPUShaderStageFlags
buffer?: GPUBufferBindingLayout
sampler?: GPUSamplerBindingLayout
texture?: GPUTextureBindingLayout
storageTexture?: GPUStorageTextureBindingLayout
Defined in lib.deno.d.ts:4329:0
interface GPUBlendComponent
srcFactor: GPUBlendFactor
dstFactor: GPUBlendFactor
operation: GPUBlendOperation
Defined in lib.deno.d.ts:4315:0
interface GPUBlendState
color: GPUBlendComponent
alpha: GPUBlendComponent
Defined in lib.deno.d.ts:4202:0
interface GPUBufferBinding
buffer: GPUBuffer
offset?: number
size?: number
Defined in lib.deno.d.ts:4139:0
interface GPUBufferBindingLayout
type?: GPUBufferBindingType
hasDynamicOffset?: boolean
minBindingSize?: number
Defined in lib.deno.d.ts:3947:0
interface GPUBufferDescriptor extends GPUObjectDescriptorBase
size: number
usage: GPUBufferUsageFlags
mappedAtCreation?: boolean
Defined in lib.deno.d.ts:4874:0
interface GPUColorDict
r: number
g: number
b: number
a: number
Defined in lib.deno.d.ts:4308:0
interface GPUColorTargetState
format: GPUTextureFormat
blend?: GPUBlendState
writeMask?: GPUColorWriteFlags
Defined in lib.deno.d.ts:4449:0
interface GPUCommandBufferDescriptor extends GPUObjectDescriptorBase
Defined in lib.deno.d.ts:4502:0
interface GPUCommandEncoderDescriptor extends GPUObjectDescriptorBase
measureExecutionTime?: boolean
Defined in lib.deno.d.ts:4225:0
interface GPUCompilationInfo
messages: ReadonlyArray<GPUCompilationMessage>
Defined in lib.deno.d.ts:4218:0
interface GPUCompilationMessage
message: string
type: GPUCompilationMessageType
lineNum: number
linePos: number
Defined in lib.deno.d.ts:4579:0
interface GPUComputePassDescriptor extends GPUObjectDescriptorBase
Defined in lib.deno.d.ts:4259:0
interface GPUComputePipelineDescriptor extends GPUPipelineDescriptorBase
compute: GPUProgrammableStage
Defined in lib.deno.d.ts:4357:0
interface GPUDepthStencilState
format: GPUTextureFormat
depthWriteEnabled?: boolean
depthCompare?: GPUCompareFunction
stencilFront?: GPUStencilFaceState
stencilBack?: GPUStencilFaceState
stencilReadMask?: number
stencilWriteMask?: number
depthBias?: number
depthBiasSlopeScale?: number
depthBiasClamp?: number
Defined in lib.deno.d.ts:3852:0
interface GPUDeviceDescriptor extends GPUObjectDescriptorBase
requiredFeatures?: GPUFeatureName[]
requiredLimits?: Record<string, number>
Defined in lib.deno.d.ts:4844:0
interface GPUDeviceLostInfo
reason: GPUDeviceLostReason | undefined
message: string
Defined in lib.deno.d.ts:4891:0
interface GPUExtent3DDict
width: number
height?: number
depthOrArrayLayers?: number
Defined in lib.deno.d.ts:4304:0
interface GPUFragmentState extends GPUProgrammableStage
targets: GPUColorTargetState[]
Defined in lib.deno.d.ts:4512:0
interface GPUImageCopyBuffer extends GPUImageDataLayout
buffer: GPUBuffer
Defined in lib.deno.d.ts:4516:0
interface GPUImageCopyTexture
texture: GPUTexture
mipLevel?: number
origin?: GPUOrigin3D
aspect?: GPUTextureAspect
Defined in lib.deno.d.ts:4506:0
interface GPUImageDataLayout
offset?: number
bytesPerRow?: number
rowsPerImage?: number
Defined in lib.deno.d.ts:4298:0
interface GPUMultisampleState
count?: number
mask?: number
alphaToCoverageEnabled?: boolean
Defined in lib.deno.d.ts:3780:0
interface GPUObjectDescriptorBase
label?: string
Defined in lib.deno.d.ts:4883:0
interface GPUOrigin3DDict
x?: number
y?: number
z?: number
Defined in lib.deno.d.ts:4244:0
interface GPUPipelineBase
getBindGroupLayout(index: number): GPUBindGroupLayout
Defined in lib.deno.d.ts:4240:0
interface GPUPipelineDescriptorBase extends GPUObjectDescriptorBase
layout?: GPUPipelineLayout
Defined in lib.deno.d.ts:4212:0
interface GPUPipelineLayoutDescriptor extends GPUObjectDescriptorBase
bindGroupLayouts: GPUBindGroupLayout[]
Defined in lib.deno.d.ts:4286:0
interface GPUPrimitiveState
topology?: GPUPrimitiveTopology
stripIndexFormat?: GPUIndexFormat
frontFace?: GPUFrontFace
cullMode?: GPUCullMode
clampDepth?: boolean
Defined in lib.deno.d.ts:4248:0
interface GPUProgrammableStage
module: GPUShaderModule
entryPoint: string
Defined in lib.deno.d.ts:4827:0
interface GPUQuerySetDescriptor extends GPUObjectDescriptorBase
type: GPUQueryType
count: number
pipelineStatistics?: GPUPipelineStatisticName[]
Defined in lib.deno.d.ts:4736:0
interface GPURenderBundleDescriptor extends GPUObjectDescriptorBase
Defined in lib.deno.d.ts:4791:0
interface GPURenderBundleEncoderDescriptor extends GPUObjectDescriptorBase
colorFormats: GPUTextureFormat[]
depthStencilFormat?: GPUTextureFormat
sampleCount?: number
Defined in lib.deno.d.ts:4708:0
interface GPURenderPassColorAttachment
view: GPUTextureView
resolveTarget?: GPUTextureView
loadValue: GPULoadOp | GPUColor
storeOp?: GPUStoreOp
Defined in lib.deno.d.ts:4716:0
interface GPURenderPassDepthStencilAttachment
view: GPUTextureView
depthLoadValue: GPULoadOp | number
depthStoreOp: GPUStoreOp
depthReadOnly?: boolean
stencilLoadValue: GPULoadOp | number
stencilStoreOp: GPUStoreOp
stencilReadOnly?: boolean
Defined in lib.deno.d.ts:4702:0
interface GPURenderPassDescriptor extends GPUObjectDescriptorBase
colorAttachments: GPURenderPassColorAttachment[]
depthStencilAttachment?: GPURenderPassDepthStencilAttachment
occlusionQuerySet?: GPUQuerySet
Defined in lib.deno.d.ts:4270:0
interface GPURenderPipelineDescriptor extends GPUPipelineDescriptorBase
vertex: GPUVertexState
primitive?: GPUPrimitiveState
depthStencil?: GPUDepthStencilState
multisample?: GPUMultisampleState
fragment?: GPUFragmentState
Defined in lib.deno.d.ts:3836:0
interface GPURequestAdapterOptions
powerPreference?: GPUPowerPreference
forceSoftware?: boolean
Defined in lib.deno.d.ts:4147:0
interface GPUSamplerBindingLayout
type?: GPUSamplerBindingType
Defined in lib.deno.d.ts:4087:0
interface GPUSamplerDescriptor extends GPUObjectDescriptorBase
addressModeU?: GPUAddressMode
addressModeV?: GPUAddressMode
addressModeW?: GPUAddressMode
magFilter?: GPUFilterMode
minFilter?: GPUFilterMode
mipmapFilter?: GPUFilterMode
lodMinClamp?: number
lodMaxClamp?: number
compare?: GPUCompareFunction
maxAnisotropy?: number
Defined in lib.deno.d.ts:4235:0
interface GPUShaderModuleDescriptor extends GPUObjectDescriptorBase
code: string | Uint32Array
sourceMap?: any
Defined in lib.deno.d.ts:4374:0
interface GPUStencilFaceState
compare?: GPUCompareFunction
failOp?: GPUStencilOperation
depthFailOp?: GPUStencilOperation
passOp?: GPUStencilOperation
Defined in lib.deno.d.ts:4177:0
interface GPUStorageTextureBindingLayout
access: GPUStorageTextureAccess
format: GPUTextureFormat
viewDimension?: GPUTextureViewDimension
Defined in lib.deno.d.ts:4156:0
interface GPUTextureBindingLayout
sampleType?: GPUTextureSampleType
viewDimension?: GPUTextureViewDimension
multisampled?: boolean
Defined in lib.deno.d.ts:4169:0
interface GPUTextureBindingLayout
sampleType?: GPUTextureSampleType
viewDimension?: GPUTextureViewDimension
multisampled?: boolean
Defined in lib.deno.d.ts:3980:0
interface GPUTextureDescriptor extends GPUObjectDescriptorBase
size: GPUExtent3D
mipLevelCount?: number
sampleCount?: number
dimension?: GPUTextureDimension
format: GPUTextureFormat
usage: GPUTextureUsageFlags
Defined in lib.deno.d.ts:4004:0
interface GPUTextureViewDescriptor extends GPUObjectDescriptorBase
format?: GPUTextureFormat
dimension?: GPUTextureViewDimension
aspect?: GPUTextureAspect
baseMipLevel?: number
mipLevelCount?: number
baseArrayLayer?: number
arrayLayerCount?: number
Defined in lib.deno.d.ts:4870:0
interface GPUUncapturedErrorEventInit extends EventInit
error?: GPUError
Defined in lib.deno.d.ts:4436:0
interface GPUVertexAttribute
format: GPUVertexFormat
offset: number
shaderLocation: number
Defined in lib.deno.d.ts:4430:0
interface GPUVertexBufferLayout
arrayStride: number
stepMode?: GPUInputStepMode
attributes: GPUVertexAttribute[]
Defined in lib.deno.d.ts:4426:0
interface GPUVertexState extends GPUProgrammableStage
buffers?: (GPUVertexBufferLayout | null)[]
Defined in lib.deno.d.ts:10:0
interface ImportMeta
Deno provides extra properties on `import.meta`. These are included here
to ensure that these are still available when using the Deno namespace in
conjunction with other type libs, like `dom`.
url: string
A string representation of the fully qualified module URL.
main: boolean
A flag that indicates if the current module is the main module that was
called when starting the program under Deno.
```ts
if (import.meta.main) {
// this was loaded as the main module, maybe do some bootstrapping
}
```
Defined in lib.deno.d.ts:30:0
interface Performance
Deno supports user timing Level 3 (see: https://w3c.github.io/user-timing)
which is not widely supported yet in other runtimes. These types are here
so that these features are still available when using the Deno namespace
in conjunction with other type libs, like `dom`.
mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark
Stores a timestamp with the associated name (a "mark").
measure(measureName: string, options?: PerformanceMeasureOptions): PerformanceMeasure
Stores the `DOMHighResTimeStamp` duration between two marks along with the
associated name (a "measure").
Defined in lib.deno.d.ts:5888:0
interface PerformanceMarkOptions
detail?: any
Metadata to be included in the mark.
startTime?: number
Timestamp to be used as the mark time.
Defined in lib.deno.d.ts:42:0
interface PerformanceMarkOptions
detail?: any
Metadata to be included in the mark.
startTime?: number
Timestamp to be used as the mark time.
Defined in lib.deno.d.ts:5896:0
interface PerformanceMeasureOptions
detail?: any
Metadata to be included in the measure.
start?: string | number
Timestamp to be used as the start time or string to be used as start
mark.
duration?: number
Duration between the start and end times.
end?: string | number
Timestamp to be used as the end time or string to be used as end mark.
Defined in lib.deno.d.ts:51:0
interface PerformanceMeasureOptions
detail?: any
Metadata to be included in the measure.
start?: string | number
Timestamp to be used as the start time or string to be used as start
mark.
duration?: number
Duration between the start and end times.
end?: string | number
Timestamp to be used as the end time or string to be used as end mark.
Defined in lib.deno.d.ts:2773:0
interface TextDecodeOptions
stream?: boolean
Defined in lib.deno.d.ts:2768:0
interface TextDecoderOptions
fatal?: boolean
ignoreBOM?: boolean
Defined in lib.deno.d.ts:2791:0
interface TextEncoderEncodeIntoResult
read: number
written: number
Defined in lib.deno.d.ts:2726:0
type EventListenerOrEventListenerObject = EventListener | EventListenerObject
Defined in lib.deno.d.ts:4100:0
type GPUAddressMode = "clamp-to-edge" | "repeat" | "mirror-repeat"
Defined in lib.deno.d.ts:4192:0
type GPUBindingResource = GPUSampler | GPUTextureView | GPUBufferBinding
Defined in lib.deno.d.ts:4335:0
type GPUBlendFactor = "zero" | "one" | "src" | "one-minus-src" | "src-alpha" | "one-minus-src-alpha" | "dst" | "one-minus-dst" | "dst-alpha" | "one-minus-dst-alpha" | "src-alpha-saturated" | "constant" | "one-minus-constant"
Defined in lib.deno.d.ts:4350:0
type GPUBlendOperation = "add" | "subtract" | "reverse-subtract" | "min" | "max"
Defined in lib.deno.d.ts:4145:0
type GPUBufferBindingType = "uniform" | "storage" | "read-only-storage"
Defined in lib.deno.d.ts:3953:0
type GPUBufferUsageFlags = number
Defined in lib.deno.d.ts:4881:0
type GPUColor = number[] | GPUColorDict
Defined in lib.deno.d.ts:4320:0
type GPUColorWriteFlags = number
Defined in lib.deno.d.ts:4104:0
type GPUCompareFunction = "never" | "less" | "equal" | "less-equal" | "greater" | "not-equal" | "greater-equal" | "always"
Defined in lib.deno.d.ts:4216:0
type GPUCompilationMessageType = "error" | "warning" | "info"
Defined in lib.deno.d.ts:4296:0
type GPUCullMode = "none" | "front" | "back"
Defined in lib.deno.d.ts:4842:0
type GPUDeviceLostReason = "destroyed"
Defined in lib.deno.d.ts:4860:0
type GPUError = GPUOutOfMemoryError | GPUValidationError
Defined in lib.deno.d.ts:4849:0
type GPUErrorFilter = "out-of-memory" | "validation"
Defined in lib.deno.d.ts:4897:0
type GPUExtent3D = number[] | GPUExtent3DDict
Defined in lib.deno.d.ts:3857:0
type GPUFeatureName = "depth-clamping" | "depth24unorm-stencil8" | "depth32float-stencil8" | "pipeline-statistics-query" | "texture-compression-bc" | "timestamp-query" | "mappable-primary-buffers" | "sampled-texture-binding-array" | "sampled-texture-array-dynamic-indexing" | "sampled-texture-array-non-uniform-indexing" | "unsized-binding-array" | "multi-draw-indirect" | "multi-draw-indirect-count" | "push-constants" | "address-mode-clamp-to-border" | "non-fill-polygon-mode" | "texture-compression-etc2" | "texture-compression-astc-ldr" | "texture-adapter-specific-format-features" | "shader-float64" | "vertex-attribute-64bit"
Defined in lib.deno.d.ts:4102:0
type GPUFilterMode = "nearest" | "linear"
Defined in lib.deno.d.ts:4294:0
type GPUFrontFace = "ccw" | "cw"
Defined in lib.deno.d.ts:4391:0
type GPUIndexFormat = "uint16" | "uint32"
Defined in lib.deno.d.ts:4424:0
type GPUInputStepMode = "vertex" | "instance"
Defined in lib.deno.d.ts:4728:0
type GPULoadOp = "load"
Defined in lib.deno.d.ts:3967:0
type GPUMapModeFlags = number
Defined in lib.deno.d.ts:4889:0
type GPUOrigin3D = number[] | GPUOrigin3DDict
Defined in lib.deno.d.ts:4835:0
type GPUPipelineStatisticName = "vertex-shader-invocations" | "clipper-invocations" | "clipper-primitives-out" | "fragment-shader-invocations" | "compute-shader-invocations"
Defined in lib.deno.d.ts:3841:0
type GPUPowerPreference = "low-power" | "high-performance"
Defined in lib.deno.d.ts:4279:0
type GPUPrimitiveTopology = "point-list" | "line-list" | "line-strip" | "triangle-list" | "triangle-strip"
Defined in lib.deno.d.ts:4833:0
type GPUQueryType = "occlusion" | "pipeline-statistics" | "timestamp"
Defined in lib.deno.d.ts:4151:0
type GPUSamplerBindingType = "filtering" | "non-filtering" | "comparison"
Defined in lib.deno.d.ts:4132:0
type GPUShaderStageFlags = number
Defined in lib.deno.d.ts:4381:0
type GPUStencilOperation = "keep" | "zero" | "replace" | "invert" | "increment-clamp" | "decrement-clamp" | "increment-wrap" | "decrement-wrap"
Defined in lib.deno.d.ts:4175:0
type GPUStorageTextureAccess = "read-only" | "write-only"
Defined in lib.deno.d.ts:4730:0
type GPUStoreOp = "store" | "discard"
Defined in lib.deno.d.ts:4022:0
type GPUTextureAspect = "all" | "stencil-only" | "depth-only"
Defined in lib.deno.d.ts:3989:0
type GPUTextureDimension = "1d" | "2d" | "3d"
Defined in lib.deno.d.ts:4024:0
type GPUTextureFormat = "r8unorm" | "r8snorm" | "r8uint" | "r8sint" | "r16uint" | "r16sint" | "r16float" | "rg8unorm" | "rg8snorm" | "rg8uint" | "rg8sint" | "r32uint" | "r32sint" | "r32float" | "rg16uint" | "rg16sint" | "rg16float" | "rgba8unorm" | "rgba8unorm-srgb" | "rgba8snorm" | "rgba8uint" | "rgba8sint" | "bgra8unorm" | "bgra8unorm-srgb" | "rgb9e5ufloat" | "rgb10a2unorm" | "rg11b10ufloat" | "rg32uint" | "rg32sint" | "rg32float" | "rgba16uint" | "rgba16sint" | "rgba16float" | "rgba32uint" | "rgba32sint" | "rgba32float" | "stencil8" | "depth16unorm" | "depth24plus" | "depth24plus-stencil8" | "depth32float" | "bc1-rgba-unorm" | "bc1-rgba-unorm-srgb" | "bc2-rgba-unorm" | "bc2-rgba-unorm-srgb" | "bc3-rgba-unorm" | "bc3-rgba-unorm-srgb" | "bc4-r-unorm" | "bc4-r-snorm" | "bc5-rg-unorm" | "bc5-rg-snorm" | "bc6h-rgb-ufloat" | "bc6h-rgb-float" | "bc7-rgba-unorm" | "bc7-rgba-unorm-srgb" | "depth24unorm-stencil8" | "depth32float-stencil8"
Defined in lib.deno.d.ts:4162:0
type GPUTextureSampleType = "float" | "unfilterable-float" | "depth" | "sint" | "uint"
Defined in lib.deno.d.ts:3991:0
type GPUTextureUsageFlags = number
Defined in lib.deno.d.ts:4014:0
type GPUTextureViewDimension = "1d" | "2d" | "2d-array" | "cube" | "cube-array" | "3d"
Defined in lib.deno.d.ts:4393:0
type GPUVertexFormat = "uint8x2" | "uint8x4" | "sint8x2" | "sint8x4" | "unorm8x2" | "unorm8x4" | "snorm8x2" | "snorm8x4" | "uint16x2" | "uint16x4" | "sint16x2" | "sint16x4" | "unorm16x2" | "unorm16x4" | "snorm16x2" | "snorm16x4" | "float16x2" | "float16x4" | "float32" | "float32x2" | "float32x3" | "float32x4" | "uint32" | "uint32x2" | "uint32x3" | "uint32x4" | "sint32" | "sint32x2" | "sint32x3" | "sint32x4"
Defined in lib.deno.d.ts:5842:0
type PerformanceEntryList = PerformanceEntry[]
Defined in lib.deno.d.ts:67:0
namespace Deno
const errors: { NotFound: ErrorConstructor; PermissionDenied: ErrorConstructor; ConnectionRefused: ErrorConstructor; ConnectionReset: ErrorConstructor; ConnectionAborted: ErrorConstructor; NotConnected: ErrorConstructor; AddrInUse: ErrorConstructor; AddrNotAvailable: ErrorConstructor; BrokenPipe: ErrorConstructor; AlreadyExists: ErrorConstructor; InvalidData: ErrorConstructor; TimedOut: ErrorConstructor; Interrupted: ErrorConstructor; WriteZero: ErrorConstructor; UnexpectedEof: ErrorConstructor; BadResource: ErrorConstructor; Http: ErrorConstructor; Busy: ErrorConstructor; NotSupported: ErrorConstructor; }
A set of error constructors that are raised by Deno APIs.
const pid: number
The current process id of the runtime.
const ppid: number
The pid of the current process's parent.
interface MemoryUsage
function memoryUsage(): MemoryUsage
Returns an object describing the memory usage of the Deno process measured
in bytes.
const noColor: boolean
Reflects the `NO_COLOR` environment variable at program start.
See: https://no-color.org/
interface TestDefinition
function test(t: TestDefinition): void
Register a test which will be run when `deno test` is used on the command
line and the containing module looks like a test module.
`fn` can be async if required.
```ts
import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
Deno.test({
name: "example test",
fn(): void {
assertEquals("world", "world");
},
});
Deno.test({
name: "example ignored test",
ignore: Deno.build.os === "windows",
fn(): void {
// This test is ignored only on Windows machines
},
});
Deno.test({
name: "example async test",
async fn() {
const decoder = new TextDecoder("utf-8");
const data = await Deno.readFile("hello_world.txt");
assertEquals(decoder.decode(data), "Hello world");
}
});
```
function test(name: string, fn: () => void | Promise<void>): void
Register a test which will be run when `deno test` is used on the command
line and the containing module looks like a test module.
`fn` can be async if required.
```ts
import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
Deno.test("My test description", ():void => {
assertEquals("hello", "hello");
});
Deno.test("My async test description", async ():Promise<void> => {
const decoder = new TextDecoder("utf-8");
const data = await Deno.readFile("hello_world.txt");
assertEquals(decoder.decode(data), "Hello world");
});
```
function exit(code?: number): never
Exit the Deno process with optional exit code. If no exit code is supplied
then Deno will exit with return code of 0.
```ts
Deno.exit(5);
```
const env: { get(key: string): string | undefined; set(key: string, value: string): void; delete(key: string): void; toObject(): { [index: string]: string; }; }
function execPath(): string
Returns the path to the current deno executable.
```ts
console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno"
```
Requires `allow-read` permission.
function chdir(directory: string | URL): void
Change the current working directory to the specified path.
```ts
Deno.chdir("/home/userA");
Deno.chdir("../userB");
Deno.chdir("C:\\Program Files (x86)\\Java");
```
Throws `Deno.errors.NotFound` if directory not found.
Throws `Deno.errors.PermissionDenied` if the user does not have access
rights
Requires --allow-read.
function cwd(): string
Return a string representing the current working directory.
If the current directory can be reached via multiple paths (due to symbolic
links), `cwd()` may return any one of them.
```ts
const currentWorkingDirectory = Deno.cwd();
```
Throws `Deno.errors.NotFound` if directory not available.
Requires --allow-read
function linkSync(oldpath: string, newpath: string): void
Synchronously creates `newpath` as a hard link to `oldpath`.
```ts
Deno.linkSync("old/name", "new/name");
```
Requires `allow-read` and `allow-write` permissions.
function link(oldpath: string, newpath: string): Promise<void>
Creates `newpath` as a hard link to `oldpath`.
```ts
await Deno.link("old/name", "new/name");
```
Requires `allow-read` and `allow-write` permissions.
enum SeekMode
interface Reader
interface ReaderSync
interface Writer
interface WriterSync
interface Closer
interface Seeker
interface SeekerSync
function copy(src: Reader, dst: Writer, options?: { bufSize: number; }): Promise<number>
@deprecated Use `copy` from https://deno.land/std/io/util.ts instead.
`Deno.copy` will be removed in Deno 2.0.
Copies from `src` to `dst` until either EOF (`null`) is read from `src` or
an error occurs. It resolves to the number of bytes copied or rejects with
the first error encountered while copying.
```ts
const source = await Deno.open("my_file.txt");
const bytesCopied1 = await Deno.copy(source, Deno.stdout);
const destination = await Deno.create("my_file_2.txt");
const bytesCopied2 = await Deno.copy(source, destination);
```
@param src The source to copy from
@param dst The destination to copy to
@param options Can be used to tune size of the buffer. Default size is 32kB
function iter(r: Reader, options?: { bufSize: number; }): AsyncIterableIterator<Uint8Array>
@deprecated Use iter from https://deno.land/std/io/util.ts instead. Deno.iter will be removed in Deno 2.0.
Turns a Reader, `r`, into an async iterator.
```ts
let f = await Deno.open("/etc/passwd");
for await (const chunk of Deno.iter(f)) {
console.log(chunk);
}
f.close();
```
Second argument can be used to tune size of a buffer.
Default size of the buffer is 32kB.
```ts
let f = await Deno.open("/etc/passwd");
const iter = Deno.iter(f, {
bufSize: 1024 * 1024
});
for await (const chunk of iter) {
console.log(chunk);
}
f.close();
```
Iterator uses an internal buffer of fixed size for efficiency; it returns
a view on that buffer on each iteration. It is therefore caller's
responsibility to copy contents of the buffer if needed; otherwise the
next iteration will overwrite contents of previously returned chunk.
function iterSync(r: ReaderSync, options?: { bufSize: number; }): IterableIterator<Uint8Array>
@deprecated Use iterSync from https://deno.land/std/io/util.ts instead. Deno.iterSync will be removed in Deno 2.0.
Turns a ReaderSync, `r`, into an iterator.
```ts
let f = Deno.openSync("/etc/passwd");
for (const chunk of Deno.iterSync(f)) {
console.log(chunk);
}
f.close();
```
Second argument can be used to tune size of a buffer.
Default size of the buffer is 32kB.
```ts
let f = await Deno.open("/etc/passwd");
const iter = Deno.iterSync(f, {
bufSize: 1024 * 1024
});
for (const chunk of iter) {
console.log(chunk);
}
f.close();
```
Iterator uses an internal buffer of fixed size for efficiency; it returns
a view on that buffer on each iteration. It is therefore caller's
responsibility to copy contents of the buffer if needed; otherwise the
next iteration will overwrite contents of previously returned chunk.
function openSync(path: string | URL, options?: OpenOptions): File
Synchronously open a file and return an instance of `Deno.File`. The
file does not need to previously exist if using the `create` or `createNew`
open options. It is the callers responsibility to close the file when finished
with it.
```ts
const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
// Do work with file
Deno.close(file.rid);
```
Requires `allow-read` and/or `allow-write` permissions depending on options.
function open(path: string | URL, options?: OpenOptions): Promise<File>
Open a file and resolve to an instance of `Deno.File`. The
file does not need to previously exist if using the `create` or `createNew`
open options. It is the callers responsibility to close the file when finished
with it.
```ts
const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
// Do work with file
Deno.close(file.rid);
```
Requires `allow-read` and/or `allow-write` permissions depending on options.
function createSync(path: string | URL): File
Creates a file if none exists or truncates an existing file and returns
an instance of `Deno.File`.
```ts
const file = Deno.createSync("/foo/bar.txt");
```
Requires `allow-read` and `allow-write` permissions.
function create(path: string | URL): Promise<File>
Creates a file if none exists or truncates an existing file and resolves to
an instance of `Deno.File`.
```ts
const file = await Deno.create("/foo/bar.txt");
```
Requires `allow-read` and `allow-write` permissions.
function readSync(rid: number, buffer: Uint8Array): number | null
Synchronously read from a resource ID (`rid`) into an array buffer (`buffer`).
Returns either the number of bytes read during the operation or EOF
(`null`) if there was nothing more to read.
It is possible for a read to successfully return with `0` bytes. This does
not indicate EOF.
This function is one of the lowest level APIs and most users should not
work with this directly, but rather use Deno.readAllSync() instead.
**It is not guaranteed that the full buffer will be read in a single call.**
```ts
// if "/foo/bar.txt" contains the text "hello world":
const file = Deno.openSync("/foo/bar.txt");
const buf = new Uint8Array(100);
const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
const text = new TextDecoder().decode(buf); // "hello world"
Deno.close(file.rid);
```
function read(rid: number, buffer: Uint8Array): Promise<number | null>
Read from a resource ID (`rid`) into an array buffer (`buffer`).
Resolves to either the number of bytes read during the operation or EOF
(`null`) if there was nothing more to read.
It is possible for a read to successfully return with `0` bytes. This does
not indicate EOF.
This function is one of the lowest level APIs and most users should not
work with this directly, but rather use Deno.readAll() instead.
**It is not guaranteed that the full buffer will be read in a single call.**
```ts
// if "/foo/bar.txt" contains the text "hello world":
const file = await Deno.open("/foo/bar.txt");
const buf = new Uint8Array(100);
const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
const text = new TextDecoder().decode(buf); // "hello world"
Deno.close(file.rid);
```
function writeSync(rid: number, data: Uint8Array): number
Synchronously write to the resource ID (`rid`) the contents of the array
buffer (`data`).
Returns the number of bytes written. This function is one of the lowest
level APIs and most users should not work with this directly, but rather use
Deno.writeAllSync() instead.
**It is not guaranteed that the full buffer will be written in a single
call.**
```ts
const encoder = new TextEncoder();
const data = encoder.encode("Hello world");
const file = Deno.openSync("/foo/bar.txt", {write: true});
const bytesWritten = Deno.writeSync(file.rid, data); // 11
Deno.close(file.rid);
```
function write(rid: number, data: Uint8Array): Promise<number>
Write to the resource ID (`rid`) the contents of the array buffer (`data`).
Resolves to the number of bytes written. This function is one of the lowest
level APIs and most users should not work with this directly, but rather use
Deno.writeAll() instead.
**It is not guaranteed that the full buffer will be written in a single
call.**
```ts
const encoder = new TextEncoder();
const data = encoder.encode("Hello world");
const file = await Deno.open("/foo/bar.txt", { write: true });
const bytesWritten = await Deno.write(file.rid, data); // 11
Deno.close(file.rid);
```
function seekSync(rid: number, offset: number, whence: SeekMode): number
Synchronously seek a resource ID (`rid`) to the given `offset` under mode
given by `whence`. The new position within the resource (bytes from the
start) is returned.
```ts
const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
// advance cursor 6 bytes
const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start);
console.log(cursorPosition); // 6
const buf = new Uint8Array(100);
file.readSync(buf);
console.log(new TextDecoder().decode(buf)); // "world"
```
The seek modes work as follows:
```ts
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
// Seek 6 bytes from the start of the file
console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
```
function seek(rid: number, offset: number, whence: SeekMode): Promise<number>
Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`.
The call resolves to the new position within the resource (bytes from the start).
```ts
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
// advance cursor 6 bytes
const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start);
console.log(cursorPosition); // 6
const buf = new Uint8Array(100);
await file.read(buf);
console.log(new TextDecoder().decode(buf)); // "world"
```
The seek modes work as follows:
```ts
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
// Seek 6 bytes from the start of the file
console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
```
function fsyncSync(rid: number): void
Synchronously flushes any pending data and metadata operations of the given file stream to disk.
```ts
const file = Deno.openSync("my_file.txt", { read: true, write: true, create: true });
Deno.writeSync(file.rid, new TextEncoder().encode("Hello World"));
Deno.ftruncateSync(file.rid, 1);
Deno.fsyncSync(file.rid);
console.log(new TextDecoder().decode(Deno.readFileSync("my_file.txt"))); // H
```
function fsync(rid: number): Promise<void>
Flushes any pending data and metadata operations of the given file stream to disk.
```ts
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.write(file.rid, new TextEncoder().encode("Hello World"));
await Deno.ftruncate(file.rid, 1);
await Deno.fsync(file.rid);
console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // H
```
function fdatasyncSync(rid: number): void
function fdatasync(rid: number): Promise<void>
Flushes any pending data operations of the given file stream to disk.
```ts
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.write(file.rid, new TextEncoder().encode("Hello World"));
await Deno.fdatasync(file.rid);
console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // Hello World
```
function close(rid: number): void
Close the given resource ID (rid) which has been previously opened, such
as via opening or creating a file. Closing a file when you are finished
with it is important to avoid leaking resources.
```ts
const file = await Deno.open("my_file.txt");
// do work with "file" object
Deno.close(file.rid);
````
class File implements Reader, ReaderSync, Writer, WriterSync, Seeker, SeekerSync, Closer
The Deno abstraction for reading and writing files.
const stdin: Reader & ReaderSync & Closer & { rid: number; }
A handle for `stdin`.
const stdout: Writer & WriterSync & Closer & { rid: number; }
A handle for `stdout`.
const stderr: Writer & WriterSync & Closer & { rid: number; }
A handle for `stderr`.
interface OpenOptions
interface ReadFileOptions
function isatty(rid: number): boolean
Check if a given resource id (`rid`) is a TTY.
```ts
// This example is system and context specific
const nonTTYRid = Deno.openSync("my_file.txt").rid;
const ttyRid = Deno.openSync("/dev/tty6").rid;
console.log(Deno.isatty(nonTTYRid)); // false
console.log(Deno.isatty(ttyRid)); // true
Deno.close(nonTTYRid);
Deno.close(ttyRid);
```
class Buffer implements Reader, ReaderSync, Writer, WriterSync
@deprecated Use Buffer from https://deno.land/std/io/buffer.ts instead. Deno.Buffer will be removed in Deno 2.0.
A variable-sized buffer of bytes with `read()` and `write()` methods.
Deno.Buffer is almost always used with some I/O like files and sockets. It
allows one to buffer up a download from a socket. Buffer grows and shrinks
as necessary.
Deno.Buffer is NOT the same thing as Node's Buffer. Node's Buffer was
created in 2009 before JavaScript had the concept of ArrayBuffers. It's
simply a non-standard ArrayBuffer.
ArrayBuffer is a fixed memory allocation. Deno.Buffer is implemented on top
of ArrayBuffer.
Based on [Go Buffer](https://golang.org/pkg/bytes/#Buffer).
function readAll(r: Reader): Promise<Uint8Array>
@deprecated Use readAll from https://deno.land/std/io/util.ts instead. Deno.readAll will be removed in Deno 2.0.
Read Reader `r` until EOF (`null`) and resolve to the content as
Uint8Array`.
```ts
// Example from stdin
const stdinContent = await Deno.readAll(Deno.stdin);
// Example from file
const file = await Deno.open("my_file.txt", {read: true});
const myFileContent = await Deno.readAll(file);
Deno.close(file.rid);
// Example from buffer
const myData = new Uint8Array(100);
// ... fill myData array with data
const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
const bufferContent = await Deno.readAll(reader);
```
function readAllSync(r: ReaderSync): Uint8Array
@deprecated Use readAllSync from https://deno.land/std/io/util.ts instead. Deno.readAllSync will be removed in Deno 2.0.
Synchronously reads Reader `r` until EOF (`null`) and returns the content
as `Uint8Array`.
```ts
// Example from stdin
const stdinContent = Deno.readAllSync(Deno.stdin);
// Example from file
const file = Deno.openSync("my_file.txt", {read: true});
const myFileContent = Deno.readAllSync(file);
Deno.close(file.rid);
// Example from buffer
const myData = new Uint8Array(100);
// ... fill myData array with data
const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
const bufferContent = Deno.readAllSync(reader);
```
function writeAll(w: Writer, arr: Uint8Array): Promise<void>
@deprecated Use writeAll from https://deno.land/std/io/util.ts instead. Deno.readAll will be removed in Deno 2.0.
Write all the content of the array buffer (`arr`) to the writer (`w`).
```ts
// Example writing to stdout
const contentBytes = new TextEncoder().encode("Hello World");
await Deno.writeAll(Deno.stdout, contentBytes);
```
```ts
// Example writing to file
const contentBytes = new TextEncoder().encode("Hello World");
const file = await Deno.open('test.file', {write: true});
await Deno.writeAll(file, contentBytes);
Deno.close(file.rid);
```
```ts
// Example writing to buffer
const contentBytes = new TextEncoder().encode("Hello World");
const writer = new Deno.Buffer();
await Deno.writeAll(writer, contentBytes);
console.log(writer.bytes().length); // 11
```
function writeAllSync(w: WriterSync, arr: Uint8Array): void
@deprecated Use writeAllSync from https://deno.land/std/io/util.ts instead. Deno.writeAllSync will be removed in Deno 2.0.
Synchronously write all the content of the array buffer (`arr`) to the
writer (`w`).
```ts
// Example writing to stdout
const contentBytes = new TextEncoder().encode("Hello World");
Deno.writeAllSync(Deno.stdout, contentBytes);
```
```ts
// Example writing to file
const contentBytes = new TextEncoder().encode("Hello World");
const file = Deno.openSync('test.file', {write: true});
Deno.writeAllSync(file, contentBytes);
Deno.close(file.rid);
```
```ts
// Example writing to buffer
const contentBytes = new TextEncoder().encode("Hello World");
const writer = new Deno.Buffer();
Deno.writeAllSync(writer, contentBytes);
console.log(writer.bytes().length); // 11
```
interface MkdirOptions
function mkdirSync(path: string | URL, options?: MkdirOptions): void
Synchronously creates a new directory with the specified path.
```ts
Deno.mkdirSync("new_dir");
Deno.mkdirSync("nested/directories", { recursive: true });
Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });
```
Defaults to throwing error if the directory already exists.
Requires `allow-write` permission.
function mkdir(path: string | URL, options?: MkdirOptions): Promise<void>
Creates a new directory with the specified path.
```ts
await Deno.mkdir("new_dir");
await Deno.mkdir("nested/directories", { recursive: true });
await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
```
Defaults to throwing error if the directory already exists.
Requires `allow-write` permission.
interface MakeTempOptions
function makeTempDirSync(options?: MakeTempOptions): string
Synchronously creates a new temporary directory in the default directory
for temporary files, unless `dir` is specified. Other optional options
include prefixing and suffixing the directory name with `prefix` and
`suffix` respectively.
The full path to the newly created directory is returned.
Multiple programs calling this function simultaneously will create different
directories. It is the caller's responsibility to remove the directory when
no longer needed.
```ts
const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76
const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
```
Requires `allow-write` permission.
function makeTempDir(options?: MakeTempOptions): Promise<string>
Creates a new temporary directory in the default directory for temporary
files, unless `dir` is specified. Other optional options include
prefixing and suffixing the directory name with `prefix` and `suffix`
respectively.
This call resolves to the full path to the newly created directory.
Multiple programs calling this function simultaneously will create different
directories. It is the caller's responsibility to remove the directory when
no longer needed.
```ts
const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76
const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
```
Requires `allow-write` permission.
function makeTempFileSync(options?: MakeTempOptions): string
Synchronously creates a new temporary file in the default directory for
temporary files, unless `dir` is specified.
Other optional options include prefixing and suffixing the directory name
with `prefix` and `suffix` respectively.
The full path to the newly created file is returned.
Multiple programs calling this function simultaneously will create different
files. It is the caller's responsibility to remove the file when no longer
needed.
```ts
const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
```
Requires `allow-write` permission.
function makeTempFile(options?: MakeTempOptions): Promise<string>
Creates a new temporary file in the default directory for temporary
files, unless `dir` is specified. Other
optional options include prefixing and suffixing the directory name with
`prefix` and `suffix` respectively.
This call resolves to the full path to the newly created file.
Multiple programs calling this function simultaneously will create different
files. It is the caller's responsibility to remove the file when no longer
needed.
```ts
const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2
const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
```
Requires `allow-write` permission.
function chmodSync(path: string | URL, mode: number): void
Synchronously changes the permission of a specific file/directory of
specified path. Ignores the process's umask.
```ts
Deno.chmodSync("/path/to/file", 0o666);
```
For a full description, see [chmod](#Deno.chmod)
NOTE: This API currently throws on Windows
Requires `allow-write` permission.
function chmod(path: string | URL, mode: number): Promise<void>
Changes the permission of a specific file/directory of specified path.
Ignores the process's umask.
```ts
await Deno.chmod("/path/to/file", 0o666);
```
The mode is a sequence of 3 octal numbers. The first/left-most number
specifies the permissions for the owner. The second number specifies the
permissions for the group. The last/right-most number specifies the
permissions for others. For example, with a mode of 0o764, the owner (7) can
read/write/execute, the group (6) can read/write and everyone else (4) can
read only.
| Number | Description |
| ------ | ----------- |
| 7 | read, write, and execute |
| 6 | read and write |
| 5 | read and execute |
| 4 | read only |
| 3 | write and execute |
| 2 | write only |
| 1 | execute only |
| 0 | no permission |
NOTE: This API currently throws on Windows
Requires `allow-write` permission.
function chownSync(path: string | URL, uid: number | null, gid: number | null): void
Synchronously change owner of a regular file or directory. This functionality
is not available on Windows.
```ts
Deno.chownSync("myFile.txt", 1000, 1002);
```
Requires `allow-write` permission.
Throws Error (not implemented) if executed on Windows
@param path path to the file
@param uid user id (UID) of the new owner, or `null` for no change
@param gid group id (GID) of the new owner, or `null` for no change
function chown(path: string | URL, uid: number | null, gid: number | null): Promise<void>
Change owner of a regular file or directory. This functionality
is not available on Windows.
```ts
await Deno.chown("myFile.txt", 1000, 1002);
```
Requires `allow-write` permission.
Throws Error (not implemented) if executed on Windows
@param path path to the file
@param uid user id (UID) of the new owner, or `null` for no change
@param gid group id (GID) of the new owner, or `null` for no change
interface RemoveOptions
function removeSync(path: string | URL, options?: RemoveOptions): void
Synchronously removes the named file or directory.
```ts
Deno.removeSync("/path/to/empty_dir/or/file");
Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });
```
Throws error if permission denied, path not found, or path is a non-empty
directory and the `recursive` option isn't set to `true`.
Requires `allow-write` permission.
function remove(path: string | URL, options?: RemoveOptions): Promise<void>
Removes the named file or directory.
```ts
await Deno.remove("/path/to/empty_dir/or/file");
await Deno.remove("/path/to/populated_dir/or/file", { recursive: true });
```
Throws error if permission denied, path not found, or path is a non-empty
directory and the `recursive` option isn't set to `true`.
Requires `allow-write` permission.
function renameSync(oldpath: string | URL, newpath: string | URL): void
Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or
directories. If `newpath` already exists and is not a directory,
`renameSync()` replaces it. OS-specific restrictions may apply when
`oldpath` and `newpath` are in different directories.
```ts
Deno.renameSync("old/path", "new/path");
```
On Unix, this operation does not follow symlinks at either path.
It varies between platforms when the operation throws errors, and if so what
they are. It's always an error to rename anything to a non-empty directory.
Requires `allow-read` and `allow-write` permissions.
function rename(oldpath: string | URL, newpath: string | URL): Promise<void>
Renames (moves) `oldpath` to `newpath`. Paths may be files or directories.
If `newpath` already exists and is not a directory, `rename()` replaces it.
OS-specific restrictions may apply when `oldpath` and `newpath` are in
different directories.
```ts
await Deno.rename("old/path", "new/path");
```
On Unix, this operation does not follow symlinks at either path.
It varies between platforms when the operation throws errors, and if so what
they are. It's always an error to rename anything to a non-empty directory.
Requires `allow-read` and `allow-write` permission.
function readTextFileSync(path: string | URL): string
Synchronously reads and returns the entire contents of a file as utf8
encoded string. Reading a directory throws an error.
```ts
const data = Deno.readTextFileSync("hello.txt");
console.log(data);
```
Requires `allow-read` permission.
function readTextFile(path: string | URL, options?: ReadFileOptions): Promise<string>
Asynchronously reads and returns the entire contents of a file as utf8
encoded string. Reading a directory throws an error.
```ts
const data = await Deno.readTextFile("hello.txt");
console.log(data);
```
Requires `allow-read` permission.
function readFileSync(path: string | URL): Uint8Array
Synchronously reads and returns the entire contents of a file as an array
of bytes. `TextDecoder` can be used to transform the bytes to string if
required. Reading a directory returns an empty data array.
```ts
const decoder = new TextDecoder("utf-8");
const data = Deno.readFileSync("hello.txt");
console.log(decoder.decode(data));
```
Requires `allow-read` permission.
function readFile(path: string | URL, options?: ReadFileOptions): Promise<Uint8Array>
Reads and resolves to the entire contents of a file as an array of bytes.
`TextDecoder` can be used to transform the bytes to string if required.
Reading a directory returns an empty data array.
```ts
const decoder = new TextDecoder("utf-8");
const data = await Deno.readFile("hello.txt");
console.log(decoder.decode(data));
```
Requires `allow-read` permission.
interface FileInfo
A FileInfo describes a file and is returned by `stat`, `lstat`,
`statSync`, `lstatSync`.
function realPathSync(path: string | URL): string
Returns absolute normalized path, with symbolic links resolved.
```ts
// e.g. given /home/alice/file.txt and current directory /home/alice
Deno.symlinkSync("file.txt", "symlink_file.txt");
const realPath = Deno.realPathSync("./file.txt");
const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
console.log(realPath); // outputs "/home/alice/file.txt"
console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
```
Requires `allow-read` permission for the target path.
Also requires `allow-read` permission for the CWD if the target path is
relative.
function realPath(path: string | URL): Promise<string>
Resolves to the absolute normalized path, with symbolic links resolved.
```ts
// e.g. given /home/alice/file.txt and current directory /home/alice
await Deno.symlink("file.txt", "symlink_file.txt");
const realPath = await Deno.realPath("./file.txt");
const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
console.log(realPath); // outputs "/home/alice/file.txt"
console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
```
Requires `allow-read` permission for the target path.
Also requires `allow-read` permission for the CWD if the target path is
relative.
interface DirEntry
function readDirSync(path: string | URL): Iterable<DirEntry>
Synchronously reads the directory given by `path` and returns an iterable
of `Deno.DirEntry`.
```ts
for (const dirEntry of Deno.readDirSync("/")) {
console.log(dirEntry.name);
}
```
Throws error if `path` is not a directory.
Requires `allow-read` permission.
function readDir(path: string | URL): AsyncIterable<DirEntry>
Reads the directory given by `path` and returns an async iterable of
`Deno.DirEntry`.
```ts
for await (const dirEntry of Deno.readDir("/")) {
console.log(dirEntry.name);
}
```
Throws error if `path` is not a directory.
Requires `allow-read` permission.
function copyFileSync(fromPath: string | URL, toPath: string | URL): void
Synchronously copies the contents and permissions of one file to another
specified path, by default creating a new file if needed, else overwriting.
Fails if target path is a directory or is unwritable.
```ts
Deno.copyFileSync("from.txt", "to.txt");
```
Requires `allow-read` permission on fromPath.
Requires `allow-write` permission on toPath.
function copyFile(fromPath: string | URL, toPath: string | URL): Promise<void>
Copies the contents and permissions of one file to another specified path,
by default creating a new file if needed, else overwriting. Fails if target
path is a directory or is unwritable.
```ts
await Deno.copyFile("from.txt", "to.txt");
```
Requires `allow-read` permission on fromPath.
Requires `allow-write` permission on toPath.
function readLinkSync(path: string | URL): string
Returns the full path destination of the named symbolic link.
```ts
Deno.symlinkSync("./test.txt", "./test_link.txt");
const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt
```
Throws TypeError if called with a hard link
Requires `allow-read` permission.
function readLink(path: string | URL): Promise<string>
Resolves to the full path destination of the named symbolic link.
```ts
await Deno.symlink("./test.txt", "./test_link.txt");
const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt
```
Throws TypeError if called with a hard link
Requires `allow-read` permission.
function lstat(path: string | URL): Promise<FileInfo>
Resolves to a `Deno.FileInfo` for the specified `path`. If `path` is a
symlink, information for the symlink will be returned instead of what it
points to.
```ts
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = await Deno.lstat("hello.txt");
assert(fileInfo.isFile);
```
Requires `allow-read` permission.
function lstatSync(path: string | URL): FileInfo
Synchronously returns a `Deno.FileInfo` for the specified `path`. If
`path` is a symlink, information for the symlink will be returned instead of
what it points to..
```ts
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = Deno.lstatSync("hello.txt");
assert(fileInfo.isFile);
```
Requires `allow-read` permission.
function stat(path: string | URL): Promise<FileInfo>
Resolves to a `Deno.FileInfo` for the specified `path`. Will always
follow symlinks.
```ts
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = await Deno.stat("hello.txt");
assert(fileInfo.isFile);
```
Requires `allow-read` permission.
function statSync(path: string | URL): FileInfo
Synchronously returns a `Deno.FileInfo` for the specified `path`. Will
always follow symlinks.
```ts
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = Deno.statSync("hello.txt");
assert(fileInfo.isFile);
```
Requires `allow-read` permission.
interface WriteFileOptions
Options for writing to a file.
function writeFileSync(path: string | URL, data: Uint8Array, options?: WriteFileOptions): void
Synchronously write `data` to the given `path`, by default creating a new
file if needed, else overwriting.
```ts
const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it
Deno.writeFileSync("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
Deno.writeFileSync("hello3.txt", data, {mode: 0o777}); // set permissions on new file
Deno.writeFileSync("hello4.txt", data, {append: true}); // add data to the end of the file
```
Requires `allow-write` permission, and `allow-read` if `options.create` is
`false`.
function writeFile(path: string | URL, data: Uint8Array, options?: WriteFileOptions): Promise<void>
Write `data` to the given `path`, by default creating a new file if needed,
else overwriting.
```ts
const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it
await Deno.writeFile("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
await Deno.writeFile("hello3.txt", data, {mode: 0o777}); // set permissions on new file
await Deno.writeFile("hello4.txt", data, {append: true}); // add data to the end of the file
```
Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
function writeTextFileSync(path: string | URL, data: string, options?: WriteFileOptions): void
Synchronously write string `data` to the given `path`, by default creating a new file if needed,
else overwriting.
```ts
Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
```
Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
function writeTextFile(path: string | URL, data: string, options?: WriteFileOptions): Promise<void>
Asynchronously write string `data` to the given `path`, by default creating a new file if needed,
else overwriting.
```ts
await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
```
Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
function truncateSync(name: string, len?: number): void
Synchronously truncates or extends the specified file, to reach the
specified `len`. If `len` is not specified then the entire file contents
are truncated.
```ts
// truncate the entire file
Deno.truncateSync("my_file.txt");
// truncate part of the file
const file = Deno.makeTempFileSync();
Deno.writeFileSync(file, new TextEncoder().encode("Hello World"));
Deno.truncateSync(file, 7);
const data = Deno.readFileSync(file);
console.log(new TextDecoder().decode(data));
```
Requires `allow-write` permission.
function truncate(name: string, len?: number): Promise<void>
Truncates or extends the specified file, to reach the specified `len`. If
`len` is not specified then the entire file contents are truncated.
```ts
// truncate the entire file
await Deno.truncate("my_file.txt");
// truncate part of the file
const file = await Deno.makeTempFile();
await Deno.writeFile(file, new TextEncoder().encode("Hello World"));
await Deno.truncate(file, 7);
const data = await Deno.readFile(file);
console.log(new TextDecoder().decode(data)); // "Hello W"
```
Requires `allow-write` permission.
interface Metrics
function metrics(): Metrics
Receive metrics from the privileged side of Deno. This is primarily used
in the development of Deno. 'Ops', also called 'bindings', are the go-between
between Deno JavaScript and Deno Rust.
> console.table(Deno.metrics())
┌─────────────────────────┬────────┐
│ (index) │ Values │
├─────────────────────────┼────────┤
│ opsDispatched │ 3 │
│ opsDispatchedSync │ 2 │
│ opsDispatchedAsync │ 1 │
│ opsDispatchedAsyncUnref │ 0 │
│ opsCompleted │ 3 │
│ opsCompletedSync │ 2 │
│ opsCompletedAsync │ 1 │
│ opsCompletedAsyncUnref │ 0 │
│ bytesSentControl │ 73 │
│ bytesSentData │ 0 │
│ bytesReceived │ 375 │
└─────────────────────────┴────────┘
function resources(): ResourceMap
Returns a map of open resource ids (rid) along with their string
representations. This is an internal API and as such resource
representation has `any` type; that means it can change any time.
```ts
console.log(Deno.resources());
// { 0: "stdin", 1: "stdout", 2: "stderr" }
Deno.openSync('../test.file');
console.log(Deno.resources());
// { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }
```
interface FsEvent
interface FsWatcher extends AsyncIterable<FsEvent>
FsWatcher is returned by `Deno.watchFs` function when you start watching
the file system. You can iterate over this interface to get the file
system events, and also you can stop watching the file system by calling
`.close()` method.
function watchFs(paths: string | string[], options?: { recursive: boolean; }): FsWatcher
Watch for file system events against one or more `paths`, which can be files
or directories. These paths must exist already. One user action (e.g.
`touch test.file`) can generate multiple file system events. Likewise,
one user action can result in multiple file paths in one event (e.g. `mv
old_name.txt new_name.txt`). Recursive option is `true` by default and,
for directories, will watch the specified directory and all sub directories.
Note that the exact ordering of the events can vary between operating systems.
```ts
const watcher = Deno.watchFs("/");
for await (const event of watcher) {
console.log(">>>> event", event);
// { kind: "create", paths: [ "/foo.txt" ] }
}
```
Requires `allow-read` permission.
Call `watcher.close()` to stop watching.
```ts
const watcher = Deno.watchFs("/");
setTimeout(() => {
watcher.close();
}, 5000);
for await (const event of watcher) {
console.log(">>>> event", event);
}
```
class Process<T extends RunOptions = RunOptions>
type ProcessStatus = { success: true; code: 0; signal: undefined; } | { success: false; code: number; signal: number; }
interface RunOptions
function run<T extends RunOptions = RunOptions>(opt: T): Process<T>
Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`,
an array of program arguments, the first of which is the binary.
```ts
const p = Deno.run({
cmd: ["echo", "hello"],
});
```
Subprocess uses same working directory as parent process unless `opt.cwd`
is specified.
Environmental variables for subprocess can be specified using `opt.env`
mapping.
By default subprocess inherits stdio of parent process. To change that
`opt.stdout`, `opt.stderr` and `opt.stdin` can be specified independently -
they can be set to either an rid of open file or set to "inherit" "piped"
or "null":
`"inherit"` The default if unspecified. The child inherits from the
corresponding parent descriptor.
`"piped"` A new pipe should be arranged to connect the parent and child
sub-processes.
`"null"` This stream will be ignored. This is the equivalent of attaching
the stream to `/dev/null`.
Details of the spawned process are returned.
Requires `allow-run` permission.
interface InspectOptions
function inspect(value: unknown, options?: InspectOptions): string
Converts the input into a string that has the same format as printed by
`console.log()`.
```ts
const obj = {
a: 10,
b: "hello",
};
const objAsString = Deno.inspect(obj); // { a: 10, b: "hello" }
console.log(obj); // prints same value as objAsString, e.g. { a: 10, b: "hello" }
```
You can also register custom inspect functions, via the symbol `Symbol.for("Deno.customInspect")`,
on objects, to control and customize the output.
```ts
class A {
x = 10;
y = "hello";
[Symbol.for("Deno.customInspect")](): string {
return "x=" + this.x + ", y=" + this.y;
}
}
const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello"
console.log(inStringFormat); // prints "x=10, y=hello"
```
Finally, you can also specify the depth to which it will format.
```ts
Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } }
```
type PermissionName = "run" | "read" | "write" | "net" | "env" | "plugin" | "hrtime"
The name of a "powerful feature" which needs permission.
type PermissionState = "granted" | "denied" | "prompt"
The current status of the permission.
interface RunPermissionDescriptor
interface ReadPermissionDescriptor
interface WritePermissionDescriptor
interface NetPermissionDescriptor
interface EnvPermissionDescriptor
interface PluginPermissionDescriptor
interface HrtimePermissionDescriptor
type PermissionDescriptor = RunPermissionDescriptor | ReadPermissionDescriptor | WritePermissionDescriptor | NetPermissionDescriptor | EnvPermissionDescriptor | PluginPermissionDescriptor | HrtimePermissionDescriptor
Permission descriptors which define a permission and can be queried,
requested, or revoked.
interface PermissionStatusEventMap
class PermissionStatus extends EventTarget
class Permissions
const permissions: Permissions
Deno's permission management API.
const build: { target: string; arch: "x86_64" | "aarch64"; os: "darwin" | "linux" | "windows"; vendor: string; env: string; }
Build related information.
const version: { deno: string; v8: string; typescript: string; }
Version related information.
const args: string[]
Returns the script arguments to the program. If for example we run a
program:
deno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd
Then `Deno.args` will contain:
[ "/etc/passwd" ]
const customInspect: unique symbol
@deprecated A symbol which can be used as a key for a custom method which will be
called when `Deno.inspect()` is called, or when the object is logged to
the console.
This symbol is deprecated since 1.9. Use `Symbol.for("Deno.customInspect")` instead.
const mainModule: string
The URL of the entrypoint module entered from the command-line.
type SymlinkOptions = { type: "file" | "dir"; }
function symlinkSync(oldpath: string | URL, newpath: string | URL, options?: SymlinkOptions): void
Creates `newpath` as a symbolic link to `oldpath`.
The options.type parameter can be set to `file` or `dir`. This argument is only
available on Windows and ignored on other platforms.
```ts
Deno.symlinkSync("old/name", "new/name");
```
Requires `allow-write` permission.
function symlink(oldpath: string | URL, newpath: string | URL, options?: SymlinkOptions): Promise<void>
Creates `newpath` as a symbolic link to `oldpath`.
The options.type parameter can be set to `file` or `dir`. This argument is only
available on Windows and ignored on other platforms.
```ts
await Deno.symlink("old/name", "new/name");
```
Requires `allow-write` permission.
function ftruncateSync(rid: number, len?: number): void
Synchronously truncates or extends the specified file stream, to reach the
specified `len`.
If `len` is not specified then the entire file contents are truncated as if len was set to 0.
if the file previously was larger than this new length, the extra data is lost.
if the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
```ts
// truncate the entire file
const file = Deno.openSync("my_file.txt", { read: true, write: true, truncate: true, create: true });
Deno.ftruncateSync(file.rid);
```
```ts
// truncate part of the file
const file = Deno.openSync("my_file.txt", { read: true, write: true, create: true });
Deno.writeSync(file.rid, new TextEncoder().encode("Hello World"));
Deno.ftruncateSync(file.rid, 7);
Deno.seekSync(file.rid, 0, Deno.SeekMode.Start);
const data = new Uint8Array(32);
Deno.readSync(file.rid, data);
console.log(new TextDecoder().decode(data)); // Hello W
```
function ftruncate(rid: number, len?: number): Promise<void>
Truncates or extends the specified file stream, to reach the specified `len`.
If `len` is not specified then the entire file contents are truncated as if len was set to 0.
If the file previously was larger than this new length, the extra data is lost.
If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
```ts
// truncate the entire file
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.ftruncate(file.rid);
```
```ts
// truncate part of the file
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.write(file.rid, new TextEncoder().encode("Hello World"));
await Deno.ftruncate(file.rid, 7);
const data = new Uint8Array(32);
await Deno.read(file.rid, data);
console.log(new TextDecoder().decode(data)); // Hello W
```
function fstatSync(rid: number): FileInfo
Synchronously returns a `Deno.FileInfo` for the given file stream.
```ts
import { assert } from "https://deno.land/std/testing/asserts.ts";
const file = Deno.openSync("file.txt", { read: true });
const fileInfo = Deno.fstatSync(file.rid);
assert(fileInfo.isFile);
```
function fstat(rid: number): Promise<FileInfo>
Returns a `Deno.FileInfo` for the given file stream.
```ts
import { assert } from "https://deno.land/std/testing/asserts.ts";
const file = await Deno.open("file.txt", { read: true });
const fileInfo = await Deno.fstat(file.rid);
assert(fileInfo.isFile);
```
Defined in lib.deno.d.ts:5260:0
namespace Deno
interface NetAddr
interface UnixAddr
type Addr = NetAddr | UnixAddr
interface Listener extends AsyncIterable<Conn>
A generic network listener for stream-oriented protocols.
interface Conn extends Reader, Writer, Closer
interface ListenOptions
function listen(options: ListenOptions & { transport: "tcp"; }): Listener
Listen announces on the local transport address.
```ts
const listener1 = Deno.listen({ port: 80 })
const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });
```
Requires `allow-net` permission.
interface ListenTlsOptions extends ListenOptions
function listenTls(options: ListenTlsOptions): Listener
Listen announces on the local transport address over TLS (transport layer
security).
```ts
const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" });
```
Requires `allow-net` permission.
interface ConnectOptions
function connect(options: ConnectOptions): Promise<Conn>
Connects to the hostname (default is "127.0.0.1") and port on the named
transport (default is "tcp"), and resolves to the connection (`Conn`).
```ts
const conn1 = await Deno.connect({ port: 80 });
const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
```
Requires `allow-net` permission for "tcp".
interface ConnectTlsOptions
function connectTls(options: ConnectTlsOptions): Promise<Conn>
Establishes a secure connection over TLS (transport layer security) using
an optional cert file, hostname (default is "127.0.0.1") and port. The
cert file is optional and if not included Mozilla's root certificates will
be used (see also https://github.com/ctz/webpki-roots for specifics)
```ts
const conn1 = await Deno.connectTls({ port: 80 });
const conn2 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 });
const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 });
const conn4 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80});
```
Requires `allow-net` permission.
function shutdown(rid: number): Promise<void>
Shutdown socket send operations.
Matches behavior of POSIX shutdown(3).
```ts
const listener = Deno.listen({ port: 80 });
const conn = await listener.accept();
Deno.shutdown(conn.rid);
```
Defined in lib.deno.d.ts:5420:0
namespace WebAssembly
class CompileError extends Error
The `WebAssembly.CompileError` object indicates an error during WebAssembly decoding or validation.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError)
class Global
A `WebAssembly.Global` object represents a global variable instance, accessible from
both JavaScript and importable/exportable across one or more `WebAssembly.Module`
instances. This allows dynamic linking of multiple modules.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global)
class Instance
A `WebAssembly.Instance` object is a stateful, executable instance of a `WebAssembly.Module`.
Instance objects contain all the Exported WebAssembly functions that allow calling into
WebAssembly code from JavaScript.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance)
class LinkError extends Error
The `WebAssembly.LinkError` object indicates an error during module instantiation
(besides traps from the start function).
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError)
class Memory
The `WebAssembly.Memory` object is a resizable `ArrayBuffer` or `SharedArrayBuffer` that
holds the raw bytes of memory accessed by a WebAssembly Instance.
A memory created by JavaScript or in WebAssembly code will be accessible and mutable
from both JavaScript and WebAssembly.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory)
class Module
A `WebAssembly.Module` object contains stateless WebAssembly code that has already been compiled
by the browser — this can be efficiently shared with Workers, and instantiated multiple times.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module)
class RuntimeError extends Error
The `WebAssembly.RuntimeError` object is the error type that is thrown whenever WebAssembly
specifies a trap.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/RuntimeError)
class Table
The `WebAssembly.Table()` object is a JavaScript wrapper object — an array-like structure
representing a WebAssembly Table, which stores function references. A table created by
JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript
and WebAssembly.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table)
interface GlobalDescriptor
The `GlobalDescriptor` describes the options you can pass to `new WebAssembly.Global()`.
interface MemoryDescriptor
The `MemoryDescriptor` describes the options you can pass to `new WebAssembly.Memory()`.
interface ModuleExportDescriptor
A `ModuleExportDescriptor` is the description of a declared export in a `WebAssembly.Module`.
interface ModuleImportDescriptor
A `ModuleImportDescriptor` is the description of a declared import in a `WebAssembly.Module`.
interface TableDescriptor
The `TableDescriptor` describes the options you can pass to `new WebAssembly.Table()`.
interface WebAssemblyInstantiatedSource
The value returned from `WebAssembly.instantiate`.
type ImportExportKind = "function" | "global" | "memory" | "table"
type TableKind = "anyfunc"
type ValueType = "f32" | "f64" | "i32" | "i64"
type ExportValue = Function | Global | Memory | Table
type Exports = Record<string, ExportValue>
type ImportValue = ExportValue | number
type ModuleImports = Record<string, ImportValue>
type Imports = Record<string, ModuleImports>
function compile(bytes: BufferSource): Promise<Module>
The `WebAssembly.compile()` function compiles WebAssembly binary code into a
`WebAssembly.Module` object. This function is useful if it is necessary to compile
a module before it can be instantiated (otherwise, the `WebAssembly.instantiate()`
function should be used).
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile)
function compileStreaming(source: Response | Promise<Response>): Promise<Module>
The `WebAssembly.compileStreaming()` function compiles a `WebAssembly.Module`
directly from a streamed underlying source. This function is useful if it is
necessary to a compile a module before it can be instantiated (otherwise, the
`WebAssembly.instantiateStreaming()` function should be used).
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming)
function instantiate(bytes: BufferSource, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>
The WebAssembly.instantiate() function allows you to compile and instantiate
WebAssembly code.
This overload takes the WebAssembly binary code, in the form of a typed
array or ArrayBuffer, and performs both compilation and instantiation in one step.
The returned Promise resolves to both a compiled WebAssembly.Module and its first
WebAssembly.Instance.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate)
function instantiate(moduleObject: Module, importObject?: Imports): Promise<Instance>
The WebAssembly.instantiate() function allows you to compile and instantiate
WebAssembly code.
This overload takes an already-compiled WebAssembly.Module and returns
a Promise that resolves to an Instance of that Module. This overload is useful
if the Module has already been compiled.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate)
function instantiateStreaming(response: Response | PromiseLike<Response>, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>
The `WebAssembly.instantiateStreaming()` function compiles and instantiates a
WebAssembly module directly from a streamed underlying source. This is the most
efficient, optimized way to load wasm code.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming)
function validate(bytes: BufferSource): boolean
The `WebAssembly.validate()` function validates a given typed array of
WebAssembly binary code, returning whether the bytes form a valid wasm
module (`true`) or not (`false`).
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate)
➜ deno doc --builtin performance
Defined in lib.deno.d.ts:3286:0
namespace performance
function now(): number
➜ deno doc --builtin WebAssembly.validate
Defined in lib.deno.d.ts:5693:2
function validate(bytes: BufferSource): boolean
The `WebAssembly.validate()` function validates a given typed array of
WebAssembly binary code, returning whether the bytes form a valid wasm
module (`true`) or not (`false`).
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate)
export interface Person {
name: string;
age: number;
}
/**
* 이름을 부르며 인사를 합니다.
* @param {Person} person
* @returns {void}
*/
export function hello(person: Person): void {
console.log(`hello, ${person.name}`);
}
/**
* 이 상수는 그냥 쓴 상수 입니다.
*/
export const HELLO = "World";
/**
* 이 클래스는 default 로 내보내기 되어 있습니다.
* 멤버 변수와 함수는 전체 문서에는 안나옵니다.
*/
export default class MyClass {
foo: number;
bar() {}
}
/**
* namespace 의 경우에는 . 을 이용해서 안의 내용을 검색할 수 있습니다.
* Namespace.Klass
*/
export namespace Namespace {
/**
* 안쪽의 문서도 밖에서 보입니다.
*/
export class Klass {}
}
➜ deno doc MyModule.ts
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:11:0
function hello(person: Person): void
이름을 부르며 인사를 합니다.
@param {Person} person
@returns {void}
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:18:0
const HELLO: "World"
이 상수는 그냥 쓴 상수 입니다.
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:24:0
class default
이 클래스는 default 로 내보내기 되어 있습니다.
멤버 변수와 함수는 전체 문서에는 안나옵니다.
foo: number
bar()
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:1:0
interface Person
name: string
age: number
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:33:0
namespace Namespace
namespace 의 경우에는 . 을 이용해서 안의 내용을 검색할 수 있습니다.
Namespace.Klass
class Klass
안쪽의 문서도 밖에서 보입니다.
➜ deno doc MyModule.ts hello
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:11:0
function hello(person: Person): void
이름을 부르며 인사를 합니다.
@param {Person} person
@returns {void}
➜ deno doc MyModule.ts Namespace.Klass
Defined in file:///Users/mark/FastCampus/deno2021/MyModule.ts:37:2
class Klass
안쪽의 문서도 밖에서 보입니다.
➜ deno help install
deno-install
Installs a script as an executable in the installation root's bin directory.
deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts
deno install https://deno.land/std/examples/colors.ts
To change the executable name, use -n/--name:
deno install --allow-net --allow-read -n serve https://deno.land/std/http/file_server.ts
The executable name is inferred by default:
- Attempt to take the file stem of the URL path. The above example would
become 'file_server'.
- If the file stem is something generic like 'main', 'mod', 'index' or 'cli',
and the path has no parent, take the file name of the parent path. Otherwise
settle with the generic name.
To change the installation root, use --root:
deno install --allow-net --allow-read --root /usr/local https://deno.land/std/http/file_server.ts
The installation root is determined, in order of precedence:
- --root option
- DENO_INSTALL_ROOT environment variable
- $HOME/.deno
These must be added to the path manually if required.
USAGE:
deno install [OPTIONS] <cmd>...
OPTIONS:
-A, --allow-all Allow all permissions
--allow-env Allow environment access
--allow-hrtime Allow high resolution time measurement
--allow-net=<allow-net> Allow network access
--allow-plugin Allow loading plugins
--allow-read=<allow-read> Allow file system read access
--allow-run Allow running subprocesses
--allow-write=<allow-write> Allow file system write access
--cert <FILE> Load certificate authority from PEM encoded file
-f, --force Forcefully overwrite existing installation
-h, --help Prints help information
-L, --log-level <log-level> Set log level [possible values: debug, info]
-n, --name <name> Executable file name
-q, --quiet Suppress diagnostic output
--root <root> Installation root
--unstable Enable unstable APIs
ARGS:
<cmd>...
~/FastCampus/deno2021
➜ deno install --allow-read --allow-net https://deno.land/std@0.103.0/http/file_server.ts
Download https://deno.land/std@0.103.0/http/file_server.ts
Download https://deno.land/std@0.103.0/io/util.ts
Download https://deno.land/std@0.103.0/http/server.ts
Download https://deno.land/std@0.103.0/flags/mod.ts
Download https://deno.land/std@0.103.0/path/mod.ts
Download https://deno.land/std@0.103.0/_util/assert.ts
Download https://deno.land/std@0.103.0/async/mod.ts
Download https://deno.land/std@0.103.0/http/_io.ts
Download https://deno.land/std@0.103.0/io/bufio.ts
Download https://deno.land/std@0.103.0/path/glob.ts
Download https://deno.land/std@0.103.0/_util/os.ts
Download https://deno.land/std@0.103.0/path/separator.ts
Download https://deno.land/std@0.103.0/path/win32.ts
Download https://deno.land/std@0.103.0/path/posix.ts
Download https://deno.land/std@0.103.0/path/common.ts
Download https://deno.land/std@0.103.0/path/_interface.ts
Download https://deno.land/std@0.103.0/bytes/mod.ts
Download https://deno.land/std@0.103.0/io/buffer.ts
Download https://deno.land/std@0.103.0/testing/asserts.ts
Download https://deno.land/std@0.103.0/async/delay.ts
Download https://deno.land/std@0.103.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.103.0/async/debounce.ts
Download https://deno.land/std@0.103.0/async/pool.ts
Download https://deno.land/std@0.103.0/async/tee.ts
Download https://deno.land/std@0.103.0/async/deferred.ts
Download https://deno.land/std@0.103.0/async/deadline.ts
Download https://deno.land/std@0.103.0/textproto/mod.ts
Download https://deno.land/std@0.103.0/http/http_status.ts
Download https://deno.land/std@0.103.0/bytes/bytes_list.ts
Download https://deno.land/std@0.103.0/path/_util.ts
Download https://deno.land/std@0.103.0/path/_constants.ts
Download https://deno.land/std@0.103.0/testing/_diff.ts
Download https://deno.land/std@0.103.0/io/types.d.ts
Check https://deno.land/std@0.103.0/http/file_server.ts
✅ Successfully installed file_server
/Users/mark/.deno/bin/file_server
~/FastCampus/deno2021 via ⬢ v14.17.4 at ☸️ docker-desktop took 5s
➜ file_server
HTTP server listening on http://0.0.0.0:4507/
~/FastCampus/deno2021
➜ deno install https://deno.land/std@0.103.0/fmt/colors.ts
✅ Successfully installed colors
/Users/mark/.deno/bin/colors
~/FastCampus/deno2021
➜ colors
if (import.meta.main) {
main();
}
--root option
DENO_INSTALL_ROOT environment variable
$HOME/.deno
~/FastCampus/deno2021
➜ deno install --allow-read --allow-net -n fs https://deno.land/std/http/file_server.ts
Download https://deno.land/std/http/file_server.ts
Warning Implicitly using master branch https://deno.land/std/http/file_server.ts
Download https://deno.land/std/path/mod.ts
Download https://deno.land/std/http/server.ts
Download https://deno.land/std/flags/mod.ts
Download https://deno.land/std/_util/assert.ts
Warning Implicitly using master branch https://deno.land/std/path/mod.ts
Download https://deno.land/std/path/_constants.ts
Download https://deno.land/std/path/win32.ts
Download https://deno.land/std/path/posix.ts
Download https://deno.land/std/path/common.ts
Download https://deno.land/std/path/separator.ts
Download https://deno.land/std/path/_interface.ts
Download https://deno.land/std/path/glob.ts
Warning Implicitly using master branch https://deno.land/std/_util/assert.ts
Warning Implicitly using master branch https://deno.land/std/flags/mod.ts
Warning Implicitly using master branch https://deno.land/std/http/server.ts
Download https://deno.land/std/encoding/utf8.ts
Download https://deno.land/std/io/bufio.ts
Download https://deno.land/std/async/mod.ts
Download https://deno.land/std/http/_io.ts
Warning Implicitly using master branch https://deno.land/std/path/posix.ts
Warning Implicitly using master branch https://deno.land/std/path/separator.ts
Warning Implicitly using master branch https://deno.land/std/path/_constants.ts
Warning Implicitly using master branch https://deno.land/std/path/win32.ts
Download https://deno.land/std/path/_util.ts
Warning Implicitly using master branch https://deno.land/std/path/common.ts
Warning Implicitly using master branch https://deno.land/std/path/_interface.ts
Warning Implicitly using master branch https://deno.land/std/path/glob.ts
Download https://deno.land/std/path/_globrex.ts
Warning Implicitly using master branch https://deno.land/std/io/bufio.ts
Download https://deno.land/std/io/util.ts
Warning Implicitly using master branch https://deno.land/std/encoding/utf8.ts
Warning Implicitly using master branch https://deno.land/std/http/_io.ts
Download https://deno.land/std/textproto/mod.ts
Download https://deno.land/std/http/http_status.ts
Warning Implicitly using master branch https://deno.land/std/async/mod.ts
Download https://deno.land/std/async/deferred.ts
Download https://deno.land/std/async/delay.ts
Download https://deno.land/std/async/mux_async_iterator.ts
Warning Implicitly using master branch https://deno.land/std/path/_util.ts
Warning Implicitly using master branch https://deno.land/std/path/_globrex.ts
Warning Implicitly using master branch https://deno.land/std/io/util.ts
Warning Implicitly using master branch https://deno.land/std/textproto/mod.ts
Download https://deno.land/std/bytes/mod.ts
Warning Implicitly using master branch https://deno.land/std/async/delay.ts
Warning Implicitly using master branch https://deno.land/std/async/deferred.ts
Warning Implicitly using master branch https://deno.land/std/async/mux_async_iterator.ts
Warning Implicitly using master branch https://deno.land/std/http/http_status.ts
Warning Implicitly using master branch https://deno.land/std/bytes/mod.ts
Compile https://deno.land/std/http/file_server.ts
✅ Successfully installed fs
/Users/mark/.deno/bin/fs
~/Deno took 4s
➜ fs
HTTP server listening on http://0.0.0.0:4507/
~/FastCampus/deno2021
➜ deno cache --lock=lock.json --lock-write welcome-with-color.ts
{
"https://raw.githubusercontent.com/denoland/deno/master/std/fmt/colors.ts": "06444b6ebc3842a4b2340d804bfa81fc5452a03513cbb81bd7f6bf8f4b8f3ac4"
}
~/FastCampus/deno2021
➜ deno cache --reload --lock=lock.json welcome-with-color.ts
Download https://raw.githubusercontent.com/denoland/deno/master/std/fmt/colors.ts
Compile file:///Users/mark/Deno/welcome-with-color.ts
~/FastCampus/deno2021
➜ deno cache --reload --lock=lock.json welcome-with-color.ts
Download https://raw.githubusercontent.com/denoland/deno/master/std/fmt/colors.ts
Compile file:///Users/mark/Deno/welcome-with-color.ts
Subresource integrity check failed --lock=lock.json
https://raw.githubusercontent.com/denoland/deno/master/std/fmt/colors.ts
~/FastCampus/deno2021
➜ deno run --lock=lock.json welcome-with-color.ts
Hello Deno
~/FastCampus/deno2021
➜ deno run --lock=lock.json welcome-with-color.ts
Subresource integrity check failed --lock=lock.json
https://raw.githubusercontent.com/denoland/deno/master/std/fmt/colors.ts
~/FastCampus/deno2021
➜ deno run --lock=lock.json --cached-only welcome-with-color.ts
error: Cannot find module "https://raw.githubusercontent.com/denoland/deno/master/std/log/mod.ts" from "file:///Users/mark/FastCampus/deno2021/welcome-with-color.ts" in cache, --cached-only is specified
➜ deno info server.ts
[1/1] Compiling file:///Users/mark/deno/deno-is-coming/server.ts
local: /Users/mark/deno/deno-is-coming/server.ts
type: TypeScript
compiled: /Users/mark/Library/Caches/deno/gen/8a1c598995d9637a1462100c9e341520af130247.js
map: /Users/mark/Library/Caches/deno/gen/8a1c598995d9637a1462100c9e341520af130247.js.map
deps:
file:///Users/mark/deno/deno-is-coming/server.ts
└─┬ https://deno.land/std@v0.5/http/server.ts
├─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/io/bufio.ts
│ ├─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/io/util.ts
│ │ ├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/strings/strings.ts
│ │ └─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path.ts
│ │ └─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/mod.ts
│ │ ├─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/win32.ts
│ │ │ ├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/constants.ts
│ │ │ └─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/utils.ts
│ │ │ └── https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/constants.ts
│ │ ├─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/posix.ts
│ │ │ ├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/constants.ts
│ │ │ └── https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/utils.ts
│ │ └── https://raw.githubusercontent.com/denoland/deno_std/v0.5/fs/path/constants.ts
│ └─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/testing/asserts.ts
│ └─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/testing/pretty.ts
│ ├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/testing/asserts.ts
│ ├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/colors/mod.ts
│ ├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/testing/diff.ts
│ └── https://raw.githubusercontent.com/denoland/deno_std/v0.5/testing/format.ts
├─┬ https://raw.githubusercontent.com/denoland/deno_std/v0.5/textproto/mod.ts
│ └── https://raw.githubusercontent.com/denoland/deno_std/v0.5/io/util.ts
├── https://raw.githubusercontent.com/denoland/deno_std/v0.5/http/http_status.ts
└── https://raw.githubusercontent.com/denoland/deno_std/v0.5/testing/asserts.ts
➜ deno help info
deno-info
Information about a module or the cache directories.
Get information about a module:
deno info https://deno.land/std/http/file_server.ts
The following information is shown:
local: Local path of the file.
type: JavaScript, TypeScript, or JSON.
compiled: Local path of compiled source code. (TypeScript only.)
map: Local path of source map. (TypeScript only.)
deps: Dependency tree of the source file.
Without any additional arguments, 'deno info' shows:
DENO_DIR: Directory containing Deno-managed files.
Remote modules cache: Subdirectory containing downloaded remote modules.
TypeScript compiler cache: Subdirectory containing TS compiler output.
USAGE:
deno info [OPTIONS] [file]
OPTIONS:
--cert <FILE> Load certificate authority from PEM encoded file
-h, --help Prints help information
-L, --log-level <log-level> Set log level [possible values: debug, info]
-q, --quiet Suppress diagnostic output
--unstable Enable unstable APIs
ARGS:
<file>
➜ deno info https://deno.land/std@0.52.0/http/file_server.ts
Download https://deno.land/std@0.52.0/http/file_server.ts
Download https://deno.land/std@0.52.0/path/mod.ts
Download https://deno.land/std@0.52.0/http/server.ts
Download https://deno.land/std@0.52.0/flags/mod.ts
Download https://deno.land/std@0.52.0/testing/asserts.ts
Download https://deno.land/std@0.52.0/fmt/colors.ts
Download https://deno.land/std@0.52.0/testing/diff.ts
Download https://deno.land/std@0.52.0/path/win32.ts
Download https://deno.land/std@0.52.0/path/posix.ts
Download https://deno.land/std@0.52.0/path/common.ts
Download https://deno.land/std@0.52.0/path/separator.ts
Download https://deno.land/std@0.52.0/path/interface.ts
Download https://deno.land/std@0.52.0/path/glob.ts
Download https://deno.land/std@0.52.0/encoding/utf8.ts
Download https://deno.land/std@0.52.0/io/bufio.ts
Download https://deno.land/std@0.52.0/async/mod.ts
Download https://deno.land/std@0.52.0/http/_io.ts
Download https://deno.land/std@0.52.0/path/_constants.ts
Download https://deno.land/std@0.52.0/path/_util.ts
Download https://deno.land/std@0.52.0/path/_globrex.ts
Download https://deno.land/std@0.52.0/textproto/mod.ts
Download https://deno.land/std@0.52.0/http/http_status.ts
Download https://deno.land/std@0.52.0/async/deferred.ts
Download https://deno.land/std@0.52.0/async/delay.ts
Download https://deno.land/std@0.52.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.52.0/io/util.ts
Download https://deno.land/std@0.52.0/bytes/mod.ts
Compile https://deno.land/std@0.52.0/http/file_server.ts
local: /Users/mark/Library/Caches/deno/deps/https/deno.land/5bd138988e9d20db1a436666628ffb3f7586934e0a2a9fe2a7b7bf4fb7f70b98
type: TypeScript
compiled: /Users/mark/Library/Caches/deno/gen/https/deno.land/std@0.52.0/http/file_server.ts.js
map: /Users/mark/Library/Caches/deno/gen/https/deno.land/std@0.52.0/http/file_server.ts.js.map
deps:
https://deno.land/std@0.52.0/http/file_server.ts
├─┬ https://deno.land/std@0.52.0/path/mod.ts
│ ├─┬ https://deno.land/std@0.52.0/path/win32.ts
│ │ ├── https://deno.land/std@0.52.0/path/_constants.ts
│ │ ├─┬ https://deno.land/std@0.52.0/path/_util.ts
│ │ │ └── https://deno.land/std@0.52.0/path/_constants.ts
│ │ └─┬ https://deno.land/std@0.52.0/testing/asserts.ts
│ │ ├── https://deno.land/std@0.52.0/fmt/colors.ts
│ │ └── https://deno.land/std@0.52.0/testing/diff.ts
│ ├─┬ https://deno.land/std@0.52.0/path/posix.ts
│ │ ├── https://deno.land/std@0.52.0/path/_constants.ts
│ │ └── https://deno.land/std@0.52.0/path/_util.ts
│ ├─┬ https://deno.land/std@0.52.0/path/common.ts
│ │ └── https://deno.land/std@0.52.0/path/separator.ts
│ ├── https://deno.land/std@0.52.0/path/separator.ts
│ ├── https://deno.land/std@0.52.0/path/interface.ts
│ └─┬ https://deno.land/std@0.52.0/path/glob.ts
│ ├── https://deno.land/std@0.52.0/path/separator.ts
│ ├── https://deno.land/std@0.52.0/path/_globrex.ts
│ ├── https://deno.land/std@0.52.0/path/mod.ts
│ └── https://deno.land/std@0.52.0/testing/asserts.ts
├─┬ https://deno.land/std@0.52.0/http/server.ts
│ ├── https://deno.land/std@0.52.0/encoding/utf8.ts
│ ├─┬ https://deno.land/std@0.52.0/io/bufio.ts
│ │ ├─┬ https://deno.land/std@0.52.0/io/util.ts
│ │ │ ├── https://deno.land/std@0.52.0/path/mod.ts
│ │ │ └── https://deno.land/std@0.52.0/encoding/utf8.ts
│ │ └── https://deno.land/std@0.52.0/testing/asserts.ts
│ ├── https://deno.land/std@0.52.0/testing/asserts.ts
│ ├─┬ https://deno.land/std@0.52.0/async/mod.ts
│ │ ├── https://deno.land/std@0.52.0/async/deferred.ts
│ │ ├── https://deno.land/std@0.52.0/async/delay.ts
│ │ └─┬ https://deno.land/std@0.52.0/async/mux_async_iterator.ts
│ │ └── https://deno.land/std@0.52.0/async/deferred.ts
│ └─┬ https://deno.land/std@0.52.0/http/_io.ts
│ ├── https://deno.land/std@0.52.0/io/bufio.ts
│ ├─┬ https://deno.land/std@0.52.0/textproto/mod.ts
│ │ ├── https://deno.land/std@0.52.0/io/util.ts
│ │ ├─┬ https://deno.land/std@0.52.0/bytes/mod.ts
│ │ │ └── https://deno.land/std@0.52.0/io/util.ts
│ │ └── https://deno.land/std@0.52.0/encoding/utf8.ts
│ ├── https://deno.land/std@0.52.0/testing/asserts.ts
│ ├── https://deno.land/std@0.52.0/encoding/utf8.ts
│ ├── https://deno.land/std@0.52.0/http/server.ts
│ └── https://deno.land/std@0.52.0/http/http_status.ts
├─┬ https://deno.land/std@0.52.0/flags/mod.ts
│ └── https://deno.land/std@0.52.0/testing/asserts.ts
└── https://deno.land/std@0.52.0/testing/asserts.ts
➜ deno help fmt
deno-fmt
Auto-format JavaScript/TypeScript source code.
deno fmt
deno fmt myfile1.ts myfile2.ts
deno fmt --check
Format stdin and write to stdout:
cat file.ts | deno fmt -
Ignore formatting code by preceding it with an ignore comment:
// deno-fmt-ignore
Ignore formatting a file by adding an ignore comment at the top of the file:
// deno-fmt-ignore-file
USAGE:
deno fmt [OPTIONS] [files]...
OPTIONS:
--check Check if the source files are formatted.
-h, --help Prints help information
-L, --log-level <log-level> Set log level [possible values: debug, info]
-q, --quiet Suppress diagnostic output
ARGS:
<files>...
formatter 로 dprint 를 사용합니다.
~/FastCampus/deno2021
➜ deno fmt --check MyModule.ts
from MyModule.ts:
02| - name: string;
02| + name: string;
error: Found 1 not formatted file
~/FastCampus/deno2021
➜ deno fmt MyModule.ts
MyModule.ts
~/FastCampus/deno2021
➜ deno fmt --check MyModule.ts
~/FastCampus/deno2021
➜ deno fmt --check
from /Users/mark/FastCampus/deno2021/MyModule.ts:
02| - name: string;
02| + name: string;
error: Found 1 not formatted file
~/FastCampus/deno2021
➜ deno fmt
/Users/mark/FastCampus/deno2021/MyModule.ts
~/FastCampus/deno2021
➜ deno fmt --check
// deno-fmt-ignore-file
~/FastCampus/deno2021
➜ deno lint welcome-with-color.ts
Checked 1 file
~/FastCampus/deno2021
➜ deno lint MyModule.ts
(no-namespace) TypeScript's `module` and `namespace` are discouraged to
use
export namespace Namespace {
^^^^^^^^^^^^^^^^^^^^^
/**
^^^^^
* 안쪽의 문서도 밖에서 보입니다.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/
^^^^^
export class Klass {}
^^^^^^^^^^^^^^^^^^^^^^^
}
^
at /Users/mark/FastCampus/deno2021/MyModule.ts:33:7
hint: Use ES2015 module syntax (`import`/`export`) to organize
the code instead
Found 1 problem
Checked 1 file
➜ deno help types
deno-types
Print runtime TypeScript declarations.
deno types > lib.deno.d.ts
The declaration file could be saved and used for typing information.
USAGE:
deno types [OPTIONS]
OPTIONS:
-h, --help Prints help information
-L, --log-level <log-level> Set log level [possible values: debug, info]
-q, --quiet Suppress diagnostic output
--unstable Enable unstable features and APIs
// d.ts 출력
➜ deno types
➜ deno types > lib.deno.d.ts
No network and filesystem access by default
➜ deno run https://deno.land/std/http/file_server.ts
error: Uncaught PermissionDenied: Requires read access to <CWD>, run again with the --allow-read flag
path = Deno.cwd();
^
at deno:core/01_core.js:106:46
at unwrapOpResult (deno:core/01_core.js:126:13)
at Object.opSync (deno:core/01_core.js:140:12)
at Object.cwd (deno:runtime/js/30_fs.js:63:17)
at Module.resolve (https://deno.land/std@0.103.0/path/posix.ts:38:19)
at https://deno.land/std@0.103.0/http/file_server.ts:54:22
➜ deno run --allow-read https://deno.land/std/http/file_server.ts
HTTP server listening on http://0.0.0.0:4507/
error: Uncaught (in promise) PermissionDenied: Requires net access to "0.0.0.0:4507", run again with the --allow-net flag
const listener = Deno.listen(addr);
^
at deno:core/01_core.js:106:46
at unwrapOpResult (deno:core/01_core.js:126:13)
at Object.opSync (deno:core/01_core.js:140:12)
at opListen (deno:extensions/net/01_net.js:38:17)
at Object.listen (deno:extensions/net/01_net.js:204:17)
at serve (https://deno.land/std@0.103.0/http/server.ts:304:25)
at listenAndServe (https://deno.land/std@0.103.0/http/server.ts:324:18)
at main (https://deno.land/std@0.103.0/http/file_server.ts:673:5)
at https://deno.land/std@0.103.0/http/file_server.ts:679:3
➜ deno run --allow-read --allow-net https://deno.land/std/http/file_server.ts
HTTP server listening on http://0.0.0.0:4507/
[2021-08-22 14:05:55] "GET / HTTP/1.1" 200
No such file or directory (os error 2)
[2021-08-22 14:05:55] "GET /favicon.ico HTTP/1.1" 404
-A, --allow-all Allow all permissions. This disables all security.
--allow-env Allow environment access for things like getting and setting of environment variables.
--allow-hrtime Allow high resolution time measurement. High resolution time can be used in timing attacks and fingerprinting.
--allow-net=\<allow-net> Allow network access. You can specify an optional, comma separated list of domains to provide a allow-list of allowed domains.
--allow-plugin Allow loading plugins. Please note that --allow-plugin is an unstable feature.
--allow-read=\<allow-read> Allow file system read access. You can specify an optional, comma separated list of directories or files to provide a allow-list of allowed file system access.
--allow-run Allow running subprocesses. Be aware that subprocesses are not run in a sandbox and therefore do not have the same security restrictions as the deno process. Therefore, use with caution.
--allow-write=\<allow-write> Allow file system write access. You can specify an optional, comma separated list of directories or files to provide a allow-list of allowed file system access.
~/FastCampus/deno2021
➜ deno run --allow-read=/Users/mark/FastCampus/deno2021 --allow-net https://deno.land/std/http/file_server.ts
HTTP server listening on http://0.0.0.0:4507/
~/FastCampus/deno2021
➜ deno run --allow-read=/Users/mark/FastCampus/deno2021,/Users/mark/Desktop --allow-net https://deno.land/std/http/file_server.ts
HTTP server listening on http://0.0.0.0:4507/
const result = await fetch("https://deno.land/");
console.log(result);
~/FastCampus/deno2021
➜ deno run --allow-net=deno.land fetch.ts
Response {
_bodySource: ReadableStream { locked: false },
contentType: "text/html",
_stream: null,
url: "https://deno.land/",
statusText: "OK",
status: 200,
headers: Headers { date: Mon, 15 Jun 2020 05:22:54 GMT, content-type: text/html, set-cookie: __cfduid=de8cd74e317340ff73dbb966ba766283d1592198573; expires=Wed, 15-Jul-20 05:22:53 GMT; path=/; domain=.deno.land; HttpOnly; SameSite=Lax; Secure, cf-ray: 5a39db1badb8996b-LAX, access-control-allow-origin: *, age: 51876, cache-control: public, max-age=0, must-revalidate, content-disposition: inline, strict-transport-security: max-age=63072000; includeSubDomains; preload, cf-cache-status: DYNAMIC, cf-request-id: 03580745450000996bd6222200000001, expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", x-vercel-cache: HIT, x-vercel-id: sfo1::9vndm-1592198574031-86fcd4834b90, x-vercel-trace: sfo1, vary: Accept-Encoding, server: cloudflare },
redirected: false,
type: "default"
}
function decorator(
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor,
) {
console.log("decorator");
}
class Welcome {
@decorator
public hello(): void {
console.log("Welcome to Deno 🦕");
}
}
function main() {
new Welcome().hello();
}
if (import.meta.main) {
main();
}
~/FastCampus/deno2021
➜ deno run decorator.ts
Check file:///Users/mark/FastCampus/deno2021/decorator.ts
decorator
Welcome to Deno 🦕
{
"compilerOptions": {
"experimentalDecorators": false
}
}
~/FastCampus/deno2021
➜ deno run -c tsconfig.json decorator.ts
Compile file:///Users/mark/FastCampus/deno2021/decorator.ts
decorator
Welcome to Deno 🦕
2-1) Deno Libraries 개요
2-2) Deno Runtime API
2-3) Deno Standard Library
2-4) Deno Third Party Modules
Deno Runtime API
function callback() {
console.log('Welcome to Deno 🦕');
}
if (import.meta.main) {
// function addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions | undefined): void;
addEventListener('hello', callback);
// function setInterval(cb: (...args: any[]) => void, delay?: number, ...args: any[]): number;
setInterval(() => {
// function dispatchEvent(event: Event): boolean;
dispatchEvent(new Event('hello'));
}, 1000);
// function clearInterval(id?: number): void;
// function setTimeout(cb: (...args: any[]) => void, delay?: number, ...args: any[]): number;
setTimeout(() => {
// function removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined): void;
removeEventListener('hello', callback);
}, 2500);
// function clearTimeout(id?: number): void;
}
~/FastCampus/deno2021
➜ deno run functions1.ts
Compile file:///Users/mark/FastCampus/deno2021/functions1.ts
Welcome to Deno 🦕
Welcome to Deno 🦕
if (import.meta.main) {
// function btoa(s: string): string;
console.log(`btoa("hello")`, btoa("hello")); // aGVsbG8=
console.log(`btoa("Hello World!")`, btoa("Hello World!")); // SGVsbG8gV29ybGQh
// function atob(s: string): string;
console.log(`atob("aGVsbG8=")`, atob("aGVsbG8=")); // hello
console.log(`atob("SGVsbG8gV29ybGQh")`, atob("SGVsbG8gV29ybGQh")); // Hello World!
}
~/FastCampus/deno2021
➜ deno run functions2.ts
Compile file:///Users/mark/FastCampus/deno2021/functions2.ts
btoa("hello") aGVsbG8=
btoa("Hello World!") SGVsbG8gV29ybGQh
atob("aGVsbG8=") hello
atob("SGVsbG8gV29ybGQh") Hello World!
// function fetch(input: Request | URL | string, init?: RequestInit): Promise<Response>;
if (import.meta.main) {
const response = await fetch("https://api.github.com/users");
const users: User[] = await response.json();
console.log(users.map((user) => user.login));
}
interface User {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
}
~/Deno
➜ deno run fetch.ts
error: Uncaught PermissionDenied: network access to "https://api.github.com/users", run again with the --allow-net flag
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async fetch ($deno$/web/fetch.ts:265:27)
at async file:///Users/mark/FastCampus/deno2021/fetch.ts:4:22
~/FastCampus/deno2021
➜ deno run --allow-net=api.github.com fetch.ts
Compile file:///Users/mark/FastCampus/deno2021/fetch.ts
[
"mojombo", "defunkt", "pjhyett",
"wycats", "ezmobius", "ivey",
"evanphx", "vanpelt", "wayneeseguin",
"brynary", "kevinclark", "technoweenie",
"macournoyer", "takeo", "caged",
"topfunky", "anotherjesse", "roland",
"lukas", "fanvsfan", "tomtt",
"railsjitsu", "nitay", "kevwil",
"KirinDave", "jamesgolick", "atmos",
"errfree", "mojodna", "bmizerany"
]
if (import.meta.main) {
console.log(Deno.cwd());
Deno.chdir("/Users/mark/Desktop");
console.log(Deno.cwd());
try {
const fileInfo = await Deno.stat("./foo.txt");
console.log(fileInfo);
if (fileInfo.isFile) {
const openedFile = await Deno.open("./foo.txt", { read: true });
const buffer = new Uint8Array(fileInfo.size);
await Deno.read(openedFile.rid, buffer);
console.log("[read buffer]", new TextDecoder().decode(buffer));
Deno.close(openedFile.rid);
await Deno.remove("./foo.txt");
}
} catch (error) {
const file = await Deno.create("./foo.txt");
const text = `Hello, Deno : ${new Date().toISOString()}`;
const data = new TextEncoder().encode(text);
await Deno.write(file.rid, data);
console.log("[write text]", text);
Deno.close(file.rid);
}
}
~/FastCampus/deno2021
➜ deno run --allow-read --allow-write file.ts
/Users/mark/FastCampus/deno2021
/Users/mark/Desktop
{
isFile: true,
isDirectory: false,
isSymlink: false,
size: 38,
mtime: 2020-06-21T13:01:23.938Z,
atime: 2020-06-21T13:01:27.367Z,
birthtime: 2020-06-21T13:01:23.937Z,
dev: 16777222,
ino: 53370832,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
blocks: 8
}
[read buffer] Hello, Deno : 2020-06-21T13:01:23.937Z
[write text] Hello, Deno : 2020-06-21T13:02:31.480Z
if (import.meta.main) {
for (let i = 0; i < Deno.args.length; i++) {
const filename = Deno.args[i];
const file = await Deno.open(filename);
await Deno.copy(file, Deno.stdout);
file.close();
}
}
~/FastCampus/deno2021
➜ deno run --allow-read cat.ts /Users/mark/Desktop/foo.txt
Hello, Deno : 2020-06-21T13:02:31.480Z%
async function print() {
const file = await Deno.open("/Users/mark/Desktop/foo.txt");
const buffer = new Uint8Array(100);
await Deno.read(file.rid, buffer);
const text = new TextDecoder().decode(buffer);
console.log(text);
Deno.close(file.rid);
}
if (import.meta.main) {
const status = await Deno.permissions.query({ name: "read" });
if (status.state !== "granted") {
throw new Error("need read permission");
}
console.log("read permission exist");
await print();
await Deno.permissions.revoke({ name: "read" });
await print();
}
~/FastCampus/deno2021
➜ deno run permission.ts
Compile file:///Users/mark/FastCampus/deno2021/permission.ts
error: Uncaught Error: need read permission
throw new Error("need read permission");
^
at file:///Users/mark/FastCampus/deno2021/permission.ts:13:11
~/FastCampus/deno2021
➜ deno run --allow-read permission.ts
read permission exist
Hello, Deno : 2020-06-21T13:02:31.480Z
error: Uncaught PermissionDenied: read access to "/Users/mark/Desktop/foo.txt", run again with the --allow-read flag
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async Object.open ($deno$/files.ts:37:15)
at async print (file:///Users/mark/FastCampus/deno2021/permission.ts:2:16)
at async file:///Users/mark/FastCampus/deno2021/permission.ts:18:3
if (import.meta.main) {
const watcher = Deno.watchFs("/Users/mark/Desktop/");
for await (const event of watcher) {
console.log(">>>> event", event);
// { kind: "create", paths: [ "/Users/mark/Desktop/foo.txt" ] }
}
}
~/FastCampus/deno2021
➜ deno run --allow-read watcher.ts
Compile file:///Users/mark/FastCampus/deno2021/watcher.ts
>>>> event { kind: "remove", paths: [ "/Users/mark/Desktop/foo.txt" ] }
>>>> event { kind: "create", paths: [ "/Users/mark/Desktop/foo.txt" ] }
>>>> event { kind: "modify", paths: [ "/Users/mark/Desktop/foo.txt" ] }
>>>> event { kind: "modify", paths: [ "/Users/mark/Desktop/foo.txt" ] }
if (import.meta.main) {
const hostname = "0.0.0.0";
const port = 8080;
const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) {
console.log(conn);
Deno.copy(conn, conn);
}
}
~/FastCampus/deno2021
➜ deno run --allow-net echo_server.ts
Compile file:///Users/mark/FastCampus/deno2021/echo_server.ts
Listening on 0.0.0.0:8080
ConnImpl {
rid: 4,
remoteAddr: { hostname: "127.0.0.1", port: 49878, transport: "tcp" },
localAddr: { hostname: "127.0.0.1", port: 8080, transport: "tcp" }
}
~/FastCampus/deno2021
➜ nc localhost 8080
hello deno
hello deno
import { BufWriter, BufReader } from "https://deno.land/std/io/bufio.ts";
import { writeResponse, readRequest } from "https://deno.land/std/http/_io.ts";
if (import.meta.main) {
const hostname = "0.0.0.0";
const port = 8080;
const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) {
const reader = new BufReader(conn);
const writer = new BufWriter(conn);
const request = await readRequest(conn, reader);
if (request === null) break;
console.log(request);
await writeResponse(writer, {
status: 200,
body: new TextEncoder().encode(JSON.stringify({ hello: "Deno" })),
});
conn.close();
}
}
~/FastCampus/deno2021
➜ deno run --allow-net http_server.ts
Compile file:///Users/mark/FastCampus/deno2021/http_server.ts
Listening on 0.0.0.0:8080
ServerRequest {
done: Promise { <pending> },
_contentLength: undefined,
_body: null,
finalized: false,
conn: ConnImpl {
rid: 4,
remoteAddr: { hostname: "127.0.0.1", port: 58829, transport: "tcp" },
localAddr: { hostname: "127.0.0.1", port: 8080, transport: "tcp" }
},
r: BufReader {
r: 572,
w: 572,
eof: false,
buf: Uint8Array(4096) [
71, 69, 84, 32, 47, 32, 72, 84, 84, 80, 47, 49, 46, 49,
13, 10, 72, 111, 115, 116, 58, 32, 108, 111, 99, 97, 108, 104,
111, 115, 116, 58, 56, 48, 56, 48, 13, 10, 67, 111, 110, 110,
101, 99, 116, 105, 111, 110, 58, 32, 107, 101, 101, 112, 45, 97,
108, 105, 118, 101, 13, 10, 67, 97, 99, 104, 101, 45, 67, 111,
110, 116, 114, 111, 108, 58, 32, 109, 97, 120, 45, 97, 103, 101,
61, 48, 13, 10, 85, 112, 103, 114, 97, 100, 101, 45, 73, 110,
115, 101,
... 3996 more items
],
rd: ConnImpl {
rid: 4,
remoteAddr: { hostname: "127.0.0.1", port: 58829, transport: "tcp" },
localAddr: { hostname: "127.0.0.1", port: 8080, transport: "tcp" }
}
},
method: "GET",
url: "/",
proto: "HTTP/1.1",
protoMinor: 1,
protoMajor: 1,
headers: Headers { host: localhost:8080, connection: keep-alive, cache-control: max-age=0, upgrade-insecure-requests: 1, user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36, accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9, sec-fetch-site: none, sec-fetch-mode: navigate, sec-fetch-user: ?1, sec-fetch-dest: document, accept-encoding: gzip, deflate, br, accept-language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7 }
}
import { listenAndServe } from "https://deno.land/std/http/server.ts";
if (import.meta.main) {
listenAndServe({
hostname: "localhost",
port: 8080,
}, (req) => {
console.log(req);
if (req.url === "/") {
req.respond({
status: 200,
body: JSON.stringify({ hello: "Deno" }),
});
return;
}
req.respond({ status: 404 });
});
}
~/FastCampus/deno2021
➜ deno run --allow-net serve.ts
Compile file:///Users/mark/FastCampus/deno2021/serve.ts
ServerRequest {
done: Promise { <pending> },
_contentLength: undefined,
_body: null,
finalized: false,
conn: ConnImpl {
rid: 4,
remoteAddr: { hostname: "::1", port: 62943, transport: "tcp" },
localAddr: { hostname: "::1", port: 8080, transport: "tcp" }
},
r: BufReader {
r: 578,
w: 578,
eof: false,
buf: Uint8Array(4096) [
71, 69, 84, 32, 47, 32, 72, 84, 84, 80, 47, 49, 46, 49,
13, 10, 72, 111, 115, 116, 58, 32, 108, 111, 99, 97, 108, 104,
111, 115, 116, 58, 56, 48, 56, 48, 13, 10, 67, 111, 110, 110,
101, 99, 116, 105, 111, 110, 58, 32, 107, 101, 101, 112, 45, 97,
108, 105, 118, 101, 13, 10, 67, 97, 99, 104, 101, 45, 67, 111,
110, 116, 114, 111, 108, 58, 32, 109, 97, 120, 45, 97, 103, 101,
61, 48, 13, 10, 85, 112, 103, 114, 97, 100, 101, 45, 73, 110,
115, 101,
... 3996 more items
],
rd: ConnImpl {
rid: 4,
remoteAddr: { hostname: "::1", port: 62943, transport: "tcp" },
localAddr: { hostname: "::1", port: 8080, transport: "tcp" }
}
},
method: "GET",
url: "/",
proto: "HTTP/1.1",
protoMinor: 1,
protoMajor: 1,
headers: Headers { host: localhost:8080, connection: keep-alive, cache-control: max-age=0, upgrade-insecure-requests: 1, user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36, accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9, sec-fetch-site: cross-site, sec-fetch-mode: navigate, sec-fetch-user: ?1, sec-fetch-dest: document, accept-encoding: gzip, deflate, br, accept-language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7 },
w: BufWriter {
usedBufferBytes: 0,
err: null,
writer: ConnImpl {
rid: 4,
remoteAddr: { hostname: "::1", port: 62943, transport: "tcp" },
localAddr: { hostname: "::1", port: 8080, transport: "tcp" }
},
buf: Uint8Array(4096) [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
... 3996 more items
]
}
}
function main(): void {
const CORSEnabled = serverArgs.cors ? true : false;
const addr = `0.0.0.0:${serverArgs.port ?? serverArgs.p ?? 4507}`;
if (serverArgs.h ?? serverArgs.help) {
console.log(`Deno File Server
Serves a local directory in HTTP.
INSTALL:
deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts
USAGE:
file_server [path] [options]
OPTIONS:
-h, --help Prints help information
-p, --port <PORT> Set port
--cors Enable CORS via the "Access-Control-Allow-Origin" header`);
Deno.exit();
}
listenAndServe(
addr,
async (req): Promise<void> => {
let normalizedUrl = posix.normalize(req.url);
try {
normalizedUrl = decodeURIComponent(normalizedUrl);
} catch (e) {
if (!(e instanceof URIError)) {
throw e;
}
}
const fsPath = posix.join(target, normalizedUrl);
let response: Response | undefined;
try {
const fileInfo = await Deno.stat(fsPath);
if (fileInfo.isDirectory) {
response = await serveDir(req, fsPath);
} else {
response = await serveFile(req, fsPath);
}
} catch (e) {
console.error(e.message);
response = await serveFallback(req, e);
} finally {
if (CORSEnabled) {
assert(response);
setCORS(response);
}
serverLog(req, response!);
req.respond(response!);
}
}
);
console.log(`HTTP server listening on http://${addr}/`);
}
if (import.meta.main) {
main();
}
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const router = new Router();
router
.get("/", (context) => {
context.response.body = { hello: "Deno" };
})
.get("/book/:id", (context) => {
if (context.params && context.params.id) {
context.response.body = context.params.id;
}
});
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
app.use((ctx) => {
ctx.response.body = "error";
});
await app.listen({ port: 8080 });
~/FastCampus/deno2021
➜ deno install -qAf --unstable https://deno.land/x/denon/denon.ts
Download https://deno.land/x/denon@v2.2.0/denon.ts
Download https://deno.land/x/denon@v2.2.0/deps.ts
Download https://deno.land/x/denon@v2.2.0/src/watcher.ts
Download https://deno.land/x/denon@v2.2.0/src/runner.ts
Download https://deno.land/x/denon@v2.2.0/src/daemon.ts
Download https://deno.land/x/denon@v2.2.0/src/cli.ts
Download https://deno.land/x/denon@v2.2.0/src/config.ts
Download https://deno.land/x/denon@v2.2.0/src/args.ts
Download https://deno.land/x/denon@v2.2.0/src/log.ts
Download https://deno.land/std@0.57.0/log/mod.ts
Download https://deno.land/std@0.57.0/log/logger.ts
Download https://deno.land/std@0.57.0/log/levels.ts
Download https://deno.land/std@0.57.0/log/handlers.ts
Download https://deno.land/std@0.57.0/fmt/colors.ts
Download https://deno.land/std@0.57.0/fs/mod.ts
Download https://deno.land/std@0.57.0/encoding/yaml.ts
Download https://deno.land/std@0.57.0/path/mod.ts
Download https://deno.land/std@0.57.0/fs/read_json.ts
Download https://deno.land/std@0.57.0/fs/write_json.ts
Download https://deno.land/std@0.57.0/async/mod.ts
Download https://deno.land/std@0.57.0/permissions/mod.ts
Download https://deno.land/x/omelette/omelette.ts
Download https://deno.land/x/denon@v2.2.0/src/scripts.ts
Download https://deno.land/x/denon@v2.2.0/src/merge.ts
Download https://deno.land/std@0.57.0/fs/exists.ts
Download https://deno.land/std@0.57.0/io/bufio.ts
Download https://deno.land/std@0.57.0/fs/empty_dir.ts
Download https://deno.land/std@0.57.0/fs/ensure_dir.ts
Download https://deno.land/std@0.57.0/fs/ensure_file.ts
Download https://deno.land/std@0.57.0/fs/ensure_link.ts
Download https://deno.land/std@0.57.0/fs/ensure_symlink.ts
Download https://deno.land/std@0.57.0/fs/expand_glob.ts
Download https://deno.land/std@0.57.0/fs/move.ts
Download https://deno.land/std@0.57.0/fs/copy.ts
Download https://deno.land/std@0.57.0/fs/read_file_str.ts
Download https://deno.land/std@0.57.0/fs/write_file_str.ts
Download https://deno.land/std@0.57.0/fs/walk.ts
Download https://deno.land/std@0.57.0/fs/eol.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/parse.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/stringify.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/schema.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/schema/mod.ts
Download https://deno.land/std@0.57.0/_util/assert.ts
Download https://deno.land/std@0.57.0/path/_constants.ts
Download https://deno.land/std@0.57.0/path/win32.ts
Download https://deno.land/std@0.57.0/path/posix.ts
Download https://deno.land/std@0.57.0/path/common.ts
Download https://deno.land/std@0.57.0/path/separator.ts
Download https://deno.land/std@0.57.0/path/_interface.ts
Download https://deno.land/std@0.57.0/path/glob.ts
Download https://deno.land/std@0.53.0/node/events.ts
Download https://deno.land/std@0.53.0/path/mod.ts
Download https://deno.land/std@0.57.0/async/deferred.ts
Download https://deno.land/std@0.57.0/async/delay.ts
Download https://deno.land/std@0.57.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.57.0/fs/_util.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/loader/loader.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/loader/loader_state.ts
Download https://deno.land/std@0.57.0/io/util.ts
Download https://deno.land/std@0.57.0/path/_util.ts
Download https://deno.land/std@0.53.0/path/win32.ts
Download https://deno.land/std@0.53.0/path/posix.ts
Download https://deno.land/std@0.53.0/path/common.ts
Download https://deno.land/std@0.53.0/path/separator.ts
Download https://deno.land/std@0.53.0/path/interface.ts
Download https://deno.land/std@0.53.0/path/glob.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/schema/core.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/schema/default.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/schema/failsafe.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/schema/json.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/dumper/dumper.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/dumper/dumper_state.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/utils.ts
Download https://deno.land/std@0.53.0/node/util.ts
Download https://deno.land/std@0.53.0/testing/asserts.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/error.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/mark.ts
Download https://deno.land/std@0.57.0/path/_globrex.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/state.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/mod.ts
Download https://deno.land/std@0.53.0/path/_globrex.ts
Download https://deno.land/std@0.53.0/path/_constants.ts
Download https://deno.land/std@0.53.0/path/_util.ts
Download https://deno.land/std@0.53.0/fmt/colors.ts
Download https://deno.land/std@0.53.0/testing/diff.ts
Download https://deno.land/std@0.53.0/node/_util/_util_callbackify.ts
Download https://deno.land/std@0.53.0/node/_utils.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/binary.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/bool.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/float.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/int.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/map.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/merge.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/nil.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/omap.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/pairs.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/seq.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/set.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/str.ts
Download https://deno.land/std@0.57.0/encoding/_yaml/type/timestamp.ts
Compile https://deno.land/x/denon@v2.2.0/denon.ts
✅ Successfully installed denon
/Users/mark/.deno/bin/denon
~/FastCampus/deno2021
➜ denon run --allow-net oak.ts
[denon] v2.2.0
[denon] watching path(s): *.*
[denon] watching extensions: ts,tsx,js,jsx,json
[denon] starting `deno run --allow-net oak.ts`
[denon] watching path(s): *.*
[denon] watching extensions: ts,tsx,js,jsx,json
[denon] restarting due to changes...
[denon] starting `deno run --allow-net oak.ts`
Compile file:///Users/mark/Deno/oak.ts
[denon] watching path(s): *.*
[denon] watching extensions: ts,tsx,js,jsx,json
[denon] restarting due to changes...
[denon] starting `deno run --allow-net oak.ts`
Compile file:///Users/mark/Deno/oak.ts
1-1) 프로젝트 개요
1-2) mysql 실행 및 설정
1-3) Nessie 를 이용한 DB 마이그레이션
1-4) 라우팅 설정하기
1-5) dotenv 를 이용한 환경 변수 설정
1-6) 로그인 처리하기
1-7) jwt 토큰 내려주기
1-8) Books 테이블 추가하기
1-9) GET /book
1-10) Error Handling
1-11) POST /book
1-12) GET /book/:id
1-13) 인증 함수 분리하기
1-14) deps.ts 파일로 의존성 관리하기
# 로그인
```
POST /login
Body { email, password }
```
# 로그아웃
```
DELETE /logout
Headers
Authorization: Bearer ${token}
```
# 책 목록보기
```
GET /book
Headers
Authorization: Bearer ${token}
```
# 책 추가하기
```
POST /book
Body { title, message, author, url }
Headers
Authorization: Bearer ${token}
```
# 책 상세보기
```
GET /book/${book.id}
Headers
Authorization: Bearer ${token}
```
# 책 수정하기
```
PATCH /book/${book.id}
Body { title, message, author, url }
Headers
Authorization: Bearer ${token}
```
# 책 삭제하기
```
DELETE /book/${book.id}
Headers
Authorization: Bearer ${token}
```
➜ docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=1234 --name books-api-mysql mysql:5.7.30
Unable to find image 'mysql:5.7.30' locally
5.7.30: Pulling from library/mysql
8559a31e96f4: Pull complete
d51ce1c2e575: Pull complete
c2344adc4858: Pull complete
fcf3ceff18fc: Pull complete
16da0c38dc5b: Pull complete
b905d1797e97: Pull complete
4b50d1c6b05c: Pull complete
d85174a87144: Pull complete
a4ad33703fa8: Pull complete
f7a5433ce20d: Pull complete
3dcd2a278b4a: Pull complete
Digest: sha256:32f9d9a069f7a735e28fd44ea944d53c61f990ba71460c5c183e610854ca4854
Status: Downloaded newer image for mysql:5.7.30
9808ce150fc5038122f1b6fd40aa33377cd9f0b3c80ab8852e4067a9e79ad7c1
// m1 mac 의 경우
➜ docker run --platform linux/amd64 -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=1234 --name books-api-mysql mysql:5.7.30
➜ docker exec -i -t books-api-mysql bash
root@9808ce150fc5:/#
root@9808ce150fc5:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.30 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> CREATE DATABASE `books-api` CHARACTER SET utf8 COLLATE utf8_general_ci;
Query OK, 1 row affected (0.01 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
➜ deno run -A --unstable https://deno.land/x/nessie/cli.ts init --dialect mysql
Download https://deno.land/x/nessie/cli.ts
Warning Implicitly using latest version (2.0.0) for https://deno.land/x/nessie/cli.ts
Download https://deno.land/x/nessie@2.0.0/cli.ts
Download https://deno.land/x/nessie@2.0.0/types.ts
Download https://deno.land/x/nessie@2.0.0/cli/templates.ts
Download https://deno.land/x/nessie@2.0.0/consts.ts
Download https://deno.land/x/nessie@2.0.0/deps.ts
Download https://deno.land/x/nessie@2.0.0/cli/utils.ts
Download https://deno.land/x/nessie@2.0.0/cli/state.ts
Download https://deno.land/x/nessie@2.0.0/cli/errors.ts
Download https://deno.land/std@0.99.0/fs/mod.ts
Download https://deno.land/std@0.99.0/path/mod.ts
Download https://deno.land/std@0.99.0/testing/asserts.ts
Download https://deno.land/x/mysql@v2.9.0/mod.ts
Download https://deno.land/x/postgres@v0.11.2/mod.ts
Download https://deno.land/x/sqlite@v2.4.0/mod.ts
Download https://deno.land/std@0.99.0/datetime/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/mod.ts
Download https://deno.land/std@0.99.0/fmt/colors.ts
Download https://deno.land/x/nessie@2.0.0/clients/AbstractClient.ts
Download https://deno.land/std@0.99.0/fs/exists.ts
Download https://deno.land/std@0.99.0/fs/copy.ts
Download https://deno.land/std@0.99.0/fs/ensure_link.ts
Download https://deno.land/std@0.99.0/fs/ensure_symlink.ts
Download https://deno.land/std@0.99.0/fs/expand_glob.ts
Download https://deno.land/std@0.99.0/fs/walk.ts
Download https://deno.land/std@0.99.0/fs/move.ts
Download https://deno.land/std@0.99.0/fs/ensure_file.ts
Download https://deno.land/std@0.99.0/fs/ensure_dir.ts
Download https://deno.land/std@0.99.0/fs/empty_dir.ts
Download https://deno.land/std@0.99.0/fs/eol.ts
Download https://deno.land/std@0.99.0/_util/os.ts
Download https://deno.land/std@0.99.0/path/common.ts
Download https://deno.land/std@0.99.0/path/_interface.ts
Download https://deno.land/std@0.99.0/path/separator.ts
Download https://deno.land/std@0.99.0/path/glob.ts
Download https://deno.land/std@0.99.0/path/posix.ts
Download https://deno.land/std@0.99.0/path/win32.ts
Download https://deno.land/std@0.99.0/datetime/formatter.ts
Download https://deno.land/x/mysql@v2.9.0/deps.ts
Download https://deno.land/x/mysql@v2.9.0/src/connection.ts
Download https://deno.land/x/mysql@v2.9.0/src/client.ts
Download https://deno.land/x/mysql@v2.9.0/src/logger.ts
Download https://deno.land/x/postgres@v0.11.2/query/query.ts
Download https://deno.land/x/postgres@v0.11.2/client.ts
Download https://deno.land/x/postgres@v0.11.2/pool.ts
Download https://deno.land/x/postgres@v0.11.2/connection/warning.ts
Download https://deno.land/x/postgres@v0.11.2/connection/connection_params.ts
Download https://deno.land/x/postgres@v0.11.2/query/transaction.ts
Download https://deno.land/x/cliffy@v0.19.2/command/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/keycode/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/table/mod.ts
Download https://deno.land/x/nessie@2.0.0/wrappers/AbstractSeed.ts
Download https://deno.land/x/nessie@2.0.0/wrappers/AbstractMigration.ts
Download https://deno.land/x/sqlite@v2.4.0/src/rows.ts
Download https://deno.land/x/sqlite@v2.4.0/src/constants.ts
Download https://deno.land/x/sqlite@v2.4.0/src/db.ts
Download https://deno.land/std@0.99.0/testing/_diff.ts
Download https://deno.land/std@0.99.0/fs/_util.ts
Download https://deno.land/std@0.99.0/_util/assert.ts
Download https://deno.land/std@0.99.0/path/_util.ts
Download https://deno.land/std@0.99.0/path/_constants.ts
Download https://deno.land/x/cliffy@v0.19.2/keycode/key_codes.ts
Download https://deno.land/x/cliffy@v0.19.2/keycode/key_code.ts
Download https://deno.land/x/mysql@v2.9.0/src/pool.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/chain.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/ansi_escapes.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/colors.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/ansi.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/cursor_position.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/tty.ts
Download https://deno.land/std@0.74.0/async/mod.ts
Download https://deno.land/x/sql_builder@v1.7.0/util.ts
Download https://deno.land/std@0.74.0/log/mod.ts
Download https://deno.land/x/bytes_formater@v1.4.0/mod.ts
Download https://deno.land/std@0.74.0/hash/mod.ts
Download https://deno.land/std@0.74.0/encoding/utf8.ts
Download https://deno.land/x/cliffy@v0.19.2/command/_errors.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/action_list.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types.ts
Download https://deno.land/x/cliffy@v0.19.2/command/command.ts
Download https://deno.land/x/cliffy@v0.19.2/command/help/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/number.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/string.ts
Download https://deno.land/x/cliffy@v0.19.2/command/type.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/child_command.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/enum.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/boolean.ts
Download https://deno.land/x/postgres@v0.11.2/connection/deferred.ts
Download https://deno.land/x/postgres@v0.11.2/connection/connection.ts
Download https://deno.land/x/postgres@v0.11.2/query/decode.ts
Download https://deno.land/x/postgres@v0.11.2/query/encode.ts
Download https://deno.land/x/cliffy@v0.19.2/table/table.ts
Download https://deno.land/x/cliffy@v0.19.2/table/cell.ts
Download https://deno.land/x/cliffy@v0.19.2/table/row.ts
Download https://deno.land/std@0.99.0/datetime/tokenizer.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/packet.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/errors.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/builders/query.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/parsers/handshake.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/parsers/err.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/builders/auth.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/packet.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth_plugin/index.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/parsers/result.ts
Download https://deno.land/x/postgres@v0.11.2/utils.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/input.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/prompt.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_input.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/confirm.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/secret.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/figures.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/number.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/checkbox.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/toggle.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_prompt.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_list.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/list.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/select.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/flags.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/string.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/_errors.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/normalize.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/number.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/validate_flags.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/boolean.ts
Download https://deno.land/x/sqlite@v2.4.0/src/wasm.ts
Download https://deno.land/x/sqlite@v2.4.0/build/sqlite.js
Download https://deno.land/x/sqlite@v2.4.0/build/sqlite.d.ts
Download https://deno.land/x/sqlite@v2.4.0/src/error.ts
Download https://deno.land/x/sqlite@v2.4.0/src/row_objects.ts
Download https://deno.land/x/mysql@v2.9.0/src/deferred.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/deps.ts
Download https://deno.land/std@0.74.0/log/handlers.ts
Download https://deno.land/std@0.74.0/_util/assert.ts
Download https://deno.land/std@0.74.0/log/logger.ts
Download https://deno.land/std@0.74.0/log/levels.ts
Download https://deno.land/x/bytes_formater@v1.4.0/format.ts
Download https://deno.land/x/bytes_formater@v1.4.0/deps.ts
Download https://deno.land/std@0.74.0/hash/hasher.ts
Download https://deno.land/std@0.74.0/hash/_wasm/hash.ts
Download https://deno.land/std@0.74.0/async/delay.ts
Download https://deno.land/std@0.74.0/async/deferred.ts
Download https://deno.land/std@0.74.0/async/pool.ts
Download https://deno.land/std@0.74.0/async/mux_async_iterator.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/complete.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/bash.ts
Download https://deno.land/x/cliffy@v0.19.2/command/deps.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/fish.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/zsh.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/_utils.ts
Download https://deno.land/x/cliffy@v0.19.2/command/_utils.ts
Download https://deno.land/x/cliffy@v0.19.2/table/border.ts
Download https://deno.land/x/cliffy@v0.19.2/table/layout.ts
Download https://deno.land/x/postgres@v0.11.2/deps.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/command.ts
Download https://deno.land/x/postgres@v0.11.2/query/decoders.ts
Download https://deno.land/x/postgres@v0.11.2/query/oid.ts
Download https://deno.land/x/sqlite@v2.4.0/build/vfs.js
Download https://deno.land/x/postgres@v0.11.2/connection/packet_writer.ts
Download https://deno.land/x/postgres@v0.11.2/connection/scram.ts
Download https://deno.land/x/postgres@v0.11.2/connection/packet_reader.ts
Download https://deno.land/x/mysql@v2.9.0/src/buffer.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/mysql_types.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/deps.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_utils.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_suggestions.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/capabilities.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth_plugin/caching_sha2_password.ts
Download https://deno.land/x/cliffy@v0.19.2/_utils/distance.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/charset.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/integer.ts
Download https://deno.land/x/cliffy@v0.19.2/command/help/_help_generator.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/integer.ts
Download https://deno.land/std@0.99.0/encoding/base64.ts
Download https://deno.land/std@0.74.0/encoding/hex.ts
Download https://deno.land/std@0.74.0/hash/_wasm/wasm.js
Download https://deno.land/std@0.74.0/encoding/base64.ts
Download https://deno.land/std@0.74.0/fmt/colors.ts
Download https://deno.land/std@0.74.0/fs/exists.ts
Download https://deno.land/std@0.74.0/io/bufio.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/_bash_completions_generator.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/_fish_completions_generator.ts
Download https://deno.land/std@0.77.0/fmt/colors.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/_zsh_completions_generator.ts
Download https://deno.land/std@0.93.0/io/bufio.ts
Download https://deno.land/std@0.93.0/hash/sha256.ts
Download https://deno.land/std@0.93.0/async/mod.ts
Download https://deno.land/std@0.93.0/encoding/base64.ts
Download https://deno.land/std@0.93.0/hash/mod.ts
Download https://deno.land/std@0.93.0/fmt/colors.ts
Download https://deno.land/std@0.93.0/bytes/mod.ts
Download https://deno.land/x/postgres@v0.11.2/query/array_parser.ts
Download https://deno.land/x/postgres@v0.11.2/query/types.ts
Download https://deno.land/x/cliffy@v0.19.2/table/utils.ts
Download https://deno.land/x/cliffy@v0.19.2/table/deps.ts
Download https://deno.land/x/mysql@v2.9.0/src/util.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth_plugin/crypt.ts
Download https://deno.land/std@0.93.0/hash/hasher.ts
Download https://deno.land/std@0.93.0/hash/_wasm/hash.ts
Download https://deno.land/std@0.93.0/async/delay.ts
Download https://deno.land/std@0.93.0/async/pool.ts
Download https://deno.land/std@0.93.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.93.0/async/deferred.ts
Download https://deno.land/std@0.93.0/io/util.ts
Download https://deno.land/std@0.93.0/_util/assert.ts
Download https://deno.land/std@0.93.0/io/buffer.ts
Download https://deno.land/std@0.74.0/bytes/mod.ts
Download https://deno.land/x/god_crypto@v0.2.0/mod.ts
Download https://deno.land/std@0.93.0/encoding/hex.ts
Download https://deno.land/std@0.93.0/hash/_wasm/wasm.js
Download https://deno.land/x/god_crypto@v0.2.0/rsa.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/basic_encoding_rule.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/rsa.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/helper.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/math.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/eme_oaep.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/primitives.ts
Download https://deno.land/std/hash/mod.ts
Warning Implicitly using latest version (0.100.0) for https://deno.land/std/hash/mod.ts
Download https://deno.land/std@0.100.0/hash/mod.ts
Download https://deno.land/std@0.100.0/hash/hasher.ts
Download https://deno.land/std@0.100.0/hash/_wasm/hash.ts
Download https://deno.land/std@0.100.0/encoding/hex.ts
Download https://deno.land/std@0.100.0/encoding/base64.ts
Download https://deno.land/std@0.100.0/hash/_wasm/wasm.js
Check https://deno.land/x/nessie/cli.ts
import {
ClientMySQL,
NessieConfig,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
const client = new ClientMySQL({
hostname: "localhost",
port: 3306,
username: "root",
password: "1234",
db: "books-api",
});
/** This is the final config object */
const config: NessieConfig = {
client,
migrationFolders: ["./db/migrations"],
seedFolders: ["./db/seeds"],
};
export default config;
➜ deno run -A --unstable https://deno.land/x/nessie/cli.ts make:migration create_users
Download https://deno.land/x/nessie/cli.ts
Warning Implicitly using latest version (2.0.0) for https://deno.land/x/nessie/cli.ts
Download https://deno.land/x/nessie@2.0.0/cli.ts
Download https://deno.land/x/nessie@2.0.0/deps.ts
Download https://deno.land/x/nessie@2.0.0/types.ts
Download https://deno.land/x/nessie@2.0.0/cli/utils.ts
Download https://deno.land/x/nessie@2.0.0/cli/state.ts
Download https://deno.land/x/nessie@2.0.0/consts.ts
Download https://deno.land/x/nessie@2.0.0/cli/templates.ts
Download https://deno.land/x/nessie@2.0.0/cli/errors.ts
Download https://deno.land/x/nessie@2.0.0/clients/AbstractClient.ts
Download https://deno.land/x/postgres@v0.11.2/mod.ts
Download https://deno.land/std@0.99.0/path/mod.ts
Download https://deno.land/x/sqlite@v2.4.0/mod.ts
Download https://deno.land/std@0.99.0/datetime/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/mod.ts
Download https://deno.land/std@0.99.0/testing/asserts.ts
Download https://deno.land/std@0.99.0/fs/mod.ts
Download https://deno.land/std@0.99.0/fmt/colors.ts
Download https://deno.land/x/mysql@v2.9.0/mod.ts
Download https://deno.land/x/nessie@2.0.0/wrappers/AbstractMigration.ts
Download https://deno.land/x/nessie@2.0.0/wrappers/AbstractSeed.ts
Download https://deno.land/std@0.99.0/datetime/formatter.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/keycode/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/table/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/command/mod.ts
Download https://deno.land/std@0.99.0/path/common.ts
Download https://deno.land/std@0.99.0/_util/os.ts
Download https://deno.land/std@0.99.0/path/win32.ts
Download https://deno.land/std@0.99.0/path/_interface.ts
Download https://deno.land/std@0.99.0/path/glob.ts
Download https://deno.land/std@0.99.0/path/separator.ts
Download https://deno.land/std@0.99.0/path/posix.ts
Download https://deno.land/std@0.99.0/fs/ensure_dir.ts
Download https://deno.land/std@0.99.0/fs/empty_dir.ts
Download https://deno.land/std@0.99.0/fs/ensure_file.ts
Download https://deno.land/std@0.99.0/fs/ensure_link.ts
Download https://deno.land/std@0.99.0/fs/ensure_symlink.ts
Download https://deno.land/std@0.99.0/fs/walk.ts
Download https://deno.land/std@0.99.0/fs/copy.ts
Download https://deno.land/std@0.99.0/fs/expand_glob.ts
Download https://deno.land/std@0.99.0/fs/exists.ts
Download https://deno.land/std@0.99.0/fs/move.ts
Download https://deno.land/std@0.99.0/fs/eol.ts
Download https://deno.land/x/mysql@v2.9.0/src/connection.ts
Download https://deno.land/x/mysql@v2.9.0/src/logger.ts
Download https://deno.land/x/mysql@v2.9.0/src/client.ts
Download https://deno.land/x/mysql@v2.9.0/deps.ts
Download https://deno.land/x/postgres@v0.11.2/connection/connection_params.ts
Download https://deno.land/x/postgres@v0.11.2/connection/warning.ts
Download https://deno.land/x/postgres@v0.11.2/pool.ts
Download https://deno.land/x/postgres@v0.11.2/query/transaction.ts
Download https://deno.land/x/postgres@v0.11.2/query/query.ts
Download https://deno.land/x/postgres@v0.11.2/client.ts
Download https://deno.land/x/sqlite@v2.4.0/src/db.ts
Download https://deno.land/x/sqlite@v2.4.0/src/rows.ts
Download https://deno.land/x/sqlite@v2.4.0/src/constants.ts
Download https://deno.land/std@0.99.0/testing/_diff.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/errors.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/parsers/handshake.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/parsers/result.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/builders/auth.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/packet.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/parsers/err.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/packet.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth_plugin/index.ts
Download https://deno.land/x/mysql@v2.9.0/src/packets/builders/query.ts
Download https://deno.land/x/bytes_formater@v1.4.0/mod.ts
Download https://deno.land/std@0.74.0/async/mod.ts
Download https://deno.land/x/sql_builder@v1.7.0/util.ts
Download https://deno.land/std@0.74.0/hash/mod.ts
Download https://deno.land/std@0.74.0/log/mod.ts
Download https://deno.land/std@0.74.0/encoding/utf8.ts
Download https://deno.land/x/postgres@v0.11.2/connection/connection.ts
Download https://deno.land/x/cliffy@v0.19.2/command/type.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/number.ts
Download https://deno.land/x/cliffy@v0.19.2/command/_errors.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/child_command.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/action_list.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/boolean.ts
Download https://deno.land/x/cliffy@v0.19.2/command/command.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/enum.ts
Download https://deno.land/x/cliffy@v0.19.2/command/help/mod.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/string.ts
Download https://deno.land/std@0.99.0/path/_constants.ts
Download https://deno.land/std@0.99.0/path/_util.ts
Download https://deno.land/std@0.99.0/fs/_util.ts
Download https://deno.land/std@0.99.0/_util/assert.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/input.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_list.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/confirm.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/prompt.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_input.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/number.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/toggle.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/secret.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/figures.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_prompt.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/checkbox.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/select.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/list.ts
Download https://deno.land/std@0.99.0/datetime/tokenizer.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/validate_flags.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/_errors.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/number.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/normalize.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/string.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/flags.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/boolean.ts
Download https://deno.land/x/cliffy@v0.19.2/table/cell.ts
Download https://deno.land/x/cliffy@v0.19.2/table/row.ts
Download https://deno.land/x/cliffy@v0.19.2/table/table.ts
Download https://deno.land/x/cliffy@v0.19.2/keycode/key_code.ts
Download https://deno.land/x/cliffy@v0.19.2/keycode/key_codes.ts
Download https://deno.land/x/mysql@v2.9.0/src/pool.ts
Download https://deno.land/x/postgres@v0.11.2/connection/deferred.ts
Download https://deno.land/x/postgres@v0.11.2/utils.ts
Download https://deno.land/x/sqlite@v2.4.0/build/sqlite.js
Download https://deno.land/x/sqlite@v2.4.0/build/sqlite.d.ts
Download https://deno.land/x/sqlite@v2.4.0/src/error.ts
Download https://deno.land/x/sqlite@v2.4.0/src/wasm.ts
Download https://deno.land/x/sqlite@v2.4.0/src/row_objects.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/tty.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/chain.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/ansi.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/ansi_escapes.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/colors.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/cursor_position.ts
Download https://deno.land/x/postgres@v0.11.2/query/decode.ts
Download https://deno.land/x/postgres@v0.11.2/query/encode.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/capabilities.ts
Download https://deno.land/x/mysql@v2.9.0/src/buffer.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth_plugin/caching_sha2_password.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/mysql_types.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/complete.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/fish.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/zsh.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/bash.ts
Download https://deno.land/x/cliffy@v0.19.2/command/deps.ts
Download https://deno.land/x/bytes_formater@v1.4.0/deps.ts
Download https://deno.land/x/bytes_formater@v1.4.0/format.ts
Download https://deno.land/std@0.74.0/hash/_wasm/hash.ts
Download https://deno.land/std@0.74.0/hash/hasher.ts
Download https://deno.land/x/cliffy@v0.19.2/command/_utils.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/_utils.ts
Download https://deno.land/x/postgres@v0.11.2/connection/packet_reader.ts
Download https://deno.land/x/postgres@v0.11.2/connection/scram.ts
Download https://deno.land/x/postgres@v0.11.2/connection/packet_writer.ts
Download https://deno.land/x/postgres@v0.11.2/deps.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth.ts
Download https://deno.land/x/mysql@v2.9.0/src/constant/charset.ts
Download https://deno.land/x/cliffy@v0.19.2/_utils/distance.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/deps.ts
Download https://deno.land/std@0.74.0/log/handlers.ts
Download https://deno.land/std@0.74.0/log/levels.ts
Download https://deno.land/std@0.74.0/log/logger.ts
Download https://deno.land/std@0.74.0/_util/assert.ts
Download https://deno.land/std@0.74.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.74.0/async/pool.ts
Download https://deno.land/std@0.74.0/async/deferred.ts
Download https://deno.land/std@0.74.0/async/delay.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_generic_suggestions.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/integer.ts
Download https://deno.land/x/cliffy@v0.19.2/command/help/_help_generator.ts
Download https://deno.land/x/cliffy@v0.19.2/command/types/command.ts
Download https://deno.land/x/cliffy@v0.19.2/prompt/_utils.ts
Download https://deno.land/x/cliffy@v0.19.2/table/layout.ts
Download https://deno.land/x/cliffy@v0.19.2/table/border.ts
Download https://deno.land/x/cliffy@v0.19.2/flags/types/integer.ts
Download https://deno.land/x/mysql@v2.9.0/src/deferred.ts
Download https://deno.land/x/sqlite@v2.4.0/build/vfs.js
Download https://deno.land/x/mysql@v2.9.0/src/util.ts
Download https://deno.land/x/mysql@v2.9.0/src/auth_plugin/crypt.ts
Download https://deno.land/x/cliffy@v0.19.2/ansi/deps.ts
Download https://deno.land/std@0.77.0/fmt/colors.ts
Download https://deno.land/std@0.74.0/io/bufio.ts
Download https://deno.land/std@0.74.0/fmt/colors.ts
Download https://deno.land/std@0.74.0/fs/exists.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/_fish_completions_generator.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/_bash_completions_generator.ts
Download https://deno.land/x/cliffy@v0.19.2/command/completions/_zsh_completions_generator.ts
Download https://deno.land/x/postgres@v0.11.2/query/decoders.ts
Download https://deno.land/x/postgres@v0.11.2/query/oid.ts
Download https://deno.land/std@0.74.0/encoding/base64.ts
Download https://deno.land/std@0.74.0/hash/_wasm/wasm.js
Download https://deno.land/std@0.74.0/encoding/hex.ts
Download https://deno.land/std@0.93.0/async/mod.ts
Download https://deno.land/std@0.93.0/encoding/base64.ts
Download https://deno.land/std@0.93.0/io/bufio.ts
Download https://deno.land/std@0.93.0/fmt/colors.ts
Download https://deno.land/std@0.93.0/bytes/mod.ts
Download https://deno.land/std@0.93.0/hash/mod.ts
Download https://deno.land/std@0.93.0/hash/sha256.ts
Download https://deno.land/x/cliffy@v0.19.2/table/utils.ts
Download https://deno.land/x/cliffy@v0.19.2/table/deps.ts
Download https://deno.land/x/god_crypto@v0.2.0/mod.ts
Download https://deno.land/std@0.99.0/encoding/base64.ts
Download https://deno.land/x/postgres@v0.11.2/query/array_parser.ts
Download https://deno.land/x/postgres@v0.11.2/query/types.ts
Download https://deno.land/std@0.74.0/bytes/mod.ts
Download https://deno.land/std@0.93.0/async/deferred.ts
Download https://deno.land/std@0.93.0/async/delay.ts
Download https://deno.land/std@0.93.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.93.0/async/pool.ts
Download https://deno.land/std@0.93.0/hash/hasher.ts
Download https://deno.land/std@0.93.0/hash/_wasm/hash.ts
Download https://deno.land/std@0.93.0/io/util.ts
Download https://deno.land/std@0.93.0/io/buffer.ts
Download https://deno.land/std@0.93.0/_util/assert.ts
Download https://deno.land/x/god_crypto@v0.2.0/rsa.ts
Download https://deno.land/std@0.93.0/hash/_wasm/wasm.js
Download https://deno.land/std@0.93.0/encoding/hex.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/rsa.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/basic_encoding_rule.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/helper.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/math.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/eme_oaep.ts
Download https://deno.land/x/god_crypto@v0.2.0/src/primitives.ts
Download https://deno.land/std/hash/mod.ts
Warning Implicitly using latest version (0.100.0) for https://deno.land/std/hash/mod.ts
Download https://deno.land/std@0.100.0/hash/mod.ts
Download https://deno.land/std@0.100.0/hash/_wasm/hash.ts
Download https://deno.land/std@0.100.0/hash/hasher.ts
Download https://deno.land/std@0.100.0/encoding/base64.ts
Download https://deno.land/std@0.100.0/encoding/hex.ts
Download https://deno.land/std@0.100.0/hash/_wasm/wasm.js
Check https://deno.land/x/nessie/cli.ts
Download https://deno.land/x/nessie@2.0.0/mod.ts
Download https://deno.land/x/nessie@2.0.0/clients/ClientMySQL.ts
Download https://deno.land/x/nessie@2.0.0/clients/ClientPostgreSQL.ts
Download https://deno.land/x/nessie@2.0.0/clients/ClientSQLite.ts
Check file:///Users/mark/FastCampus/deno2021/books-api-deno/nessie.config.ts
Created migration /Users/mark/FastCampus/deno2021/books-api-deno/db/migrations/20210712225503_create_users.ts
import {
AbstractMigration,
Info,
ClientMySQL,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
export default class extends AbstractMigration<ClientMySQL> {
/** Runs on migrate */
async up(info: Info): Promise<void> {
// await this.client.queryArray("CREATE TABLE table1 (id int)");
}
/** Runs on rollback */
async down(info: Info): Promise<void> {
// await this.client.queryArray("DROP TABLE table1");
}
}
import {
AbstractMigration,
Info,
ClientMySQL,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
import { v4 } from "https://deno.land/std@0.100.0/uuid/mod.ts";
import * as bcrypt from "https://deno.land/x/bcrypt@v0.2.4/mod.ts";
export default class extends AbstractMigration<ClientMySQL> {
/** Runs on migrate */
async up(info: Info): Promise<void> {
await this.client.query(`
CREATE TABLE Users (
userId varchar(36) NOT NULL,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp,
updated_at timestamp NOT NULL DEFAULT current_timestamp,
PRIMARY KEY (userId)
);
`);
const uuid = v4.generate();
const name = "Mark Lee";
const email = "2woongjae@gmail.com";
const hashed = await bcrypt.hash("deno1234");
await this.client.query(
`INSERT INTO Users VALUES ('${uuid}', '${name}', '${email}', '${hashed}', DEFAULT, DEFAULT)`
);
}
/** Runs on rollback */
async down(info: Info): Promise<void> {
await this.client.query("DROP TABLE IF EXISTS Users");
}
}
➜ deno run -A --unstable https://deno.land/x/nessie/cli.ts migrate
INFO connecting localhost:3306
INFO connected to localhost:3306
Starting migration of 1 files
----
Migrating 20210712225503_create_users.ts
Check file:///Users/mark/FastCampus/deno2021/books-api-deno/db/migrations/20210712225503_create_users.ts
Done in 7.25 seconds
----
Migrations completed in 7.25 seconds
INFO close connection
➜ deno run -A --unstable https://deno.land/x/nessie/cli.ts rollback
INFO connecting localhost:3306
INFO connected to localhost:3306
Starting rollback of 1 files
----
Rolling back 20210712225503_create_users.ts
Check file:///Users/mark/FastCampus/deno2021/books-api-deno/db/migrations/20210712225503_create_users.ts
Done in 6.91 seconds
----
Rollback completed in 6.91 seconds
INFO close connection
import {
AbstractMigration,
Info,
ClientMySQL,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
import Dex from "https://deno.land/x/dex@1.0.2/mod.ts";
import { v4 } from "https://deno.land/std/uuid/mod.ts";
import * as bcrypt from "https://deno.land/x/bcrypt/mod.ts";
export default class extends AbstractMigration<ClientMySQL> {
/** Runs on migrate */
async up({ dialect }: Info): Promise<void> {
const query = Dex({ client: dialect }).schema.createTable(
"Users",
(table: any) => {
table.string("userId", 36).primary().notNullable();
table.string("name", 255).notNullable();
table.string("email", 255).notNullable();
table.string("password", 255).notNullable();
table.timestamps(null, true);
}
);
await this.client.query(query);
const uuid = v4.generate();
const name = "Mark Lee";
const email = "2woongjae@gmail.com";
const hashed = await bcrypt.hash("deno1234");
await this.client.query(
`INSERT INTO Users VALUES ('${uuid}', '${name}', '${email}', '${hashed}', DEFAULT, DEFAULT);`
);
}
/** Runs on rollback */
async down({ dialect }: Info): Promise<void> {
const query = Dex({ client: dialect }).schema.dropTable("Users");
await this.client.query(query);
}
}
import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
import notFound from "./not_found.ts";
const port = 5000;
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
app.use(notFound);
await app.listen({ port });
import { Router } from "https://deno.land/x/oak/mod.ts";
import UserController from "./controllers/UserController.ts";
import BookController from "./controllers/BookController.ts";
const router = new Router();
const userController = new UserController();
const bookController = new BookController();
router
.post("/login", userController.login)
.delete("/logout", userController.logout)
.post("/book", bookController.createBook)
.get("/book", bookController.getBooks)
.get("/book/:id", bookController.getBook)
.patch("/book/:id", bookController.updateBook)
.delete("/book/:id", bookController.deleteBook);
export default router;
import { Context } from "https://deno.land/x/oak/mod.ts";
export default function notFound(context: Context) {
context.response.status = 404;
context.response.body = { error: "Not Found" };
}
import { RouterContext } from "https://deno.land/x/oak/mod.ts";
export default class UserController {
public login(context: RouterContext) {
context.response.body = "login";
}
public logout(context: RouterContext) {
context.response.body = "logout";
}
}
import { RouterContext } from "https://deno.land/x/oak/mod.ts";
export default class BookController {
public createBook(context: RouterContext) {
context.response.body = "createBook";
}
public getBooks(context: RouterContext) {
context.response.body = "getBooks";
}
public getBook(context: RouterContext) {
const id = context.params?.id || null;
context.response.body = "getBook : " + id;
}
public updateBook(context: RouterContext) {
const id = context.params?.id || null;
context.response.body = "updateBook : " + id;
}
public deleteBook(context: RouterContext) {
const id = context.params?.id || null;
context.response.body = "deleteBook : " + id;
}
}
➜ deno run --allow-net main.ts
PORT=8888
import { config } from "https://deno.land/x/dotenv/mod.ts";
import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
import notFound from "./not_found.ts";
const env = config();
const port = Number(env.PORT) || 5000;
const app = new Application();
app.use(router.routes());
app.use(notFound);
await app.listen({ port });
➜ deno run --allow-net --allow-read main.ts
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
export default class UserController {
public async login(context: RouterContext) {
const result = (await context.request.body()) as BodyForm;
console.log(result.type, await result.value);
context.response.body = "login";
}
public logout(context: RouterContext) {
context.response.body = "logout";
}
}
// form URLSearchParams {
// [Symbol(list)]: [ [ "email", "2woongjae@gmail.com" ], [ "password", "1234" ] ],
// [Symbol("url object")]: null,
// [Symbol("[[webidl.brand]]")]: Symbol("[[webidl.brand]]")
//}
declare class URLSearchParams {
constructor(
init?: string[][] | Record<string, string> | string | URLSearchParams,
);
static toString(): string;
append(name: string, value: string): void;
delete(name: string): void;
getAll(name: string): string[];
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
sort(): void;
forEach(
callbackfn: (value: string, key: string, parent: this) => void,
thisArg?: any,
): void;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
entries(): IterableIterator<[string, string]>;
[Symbol.iterator](): IterableIterator<[string, string]>;
toString(): string;
}
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
export default class UserController {
public async login(context: RouterContext) {
const { type, value } = (await context.request.body()) as BodyForm;
const params = await value;
const email = params.get("email");
const password = params.get("password");
console.log(email, password); // 2woongjae@gmail.com deno1234
context.response.body = "login";
}
public logout(context: RouterContext) {
context.response.body = "logout";
}
}
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
export default class UserController {
public async login(context: RouterContext) {
const { type, value } = (await context.request.body()) as BodyForm;
const params = await value;
const email = params.get("email");
const password = params.get("password");
console.log(email, password); // 2woongjae@gmail.com deno1234
if (email === null || password === null) {
context.response.status = 422;
context.response.body = { error: "email or password required" };
return;
}
context.response.body = "login";
}
public logout(context: RouterContext) {
context.response.body = "logout";
}
}
import {
ClientMySQL,
NessieConfig,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
export const connectionOptions = {
hostname: "localhost",
port: 3306,
username: "root",
password: "1234",
db: "books-api",
};
const client = new ClientMySQL(connectionOptions);
/** This is the final config object */
const config: NessieConfig = {
client,
migrationFolders: ["./db/migrations"],
seedFolders: ["./db/seeds"],
};
export default config;
import { Client } from "https://deno.land/x/mysql/mod.ts";
import { connectionOptions } from "../nessie.config.ts";
const client = await new Client().connect(connectionOptions);
export default client;
import client from "./config.ts";
export interface User {
userId: string;
name: string;
email: string;
password: string;
created_at: Date;
updated_at: Date;
}
export async function getUserByEmail(email: string): Promise<User> {
const { rows } = await client.execute(
`SELECT * FROM Users WHERE email = '${email}'`
);
if (rows === undefined) throw new Error();
if (rows.length !== 1) throw new Error();
return rows[0];
}
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
import { getUserByEmail } from "../models/User.ts";
import * as bcrypt from "https://deno.land/x/bcrypt@v0.2.4/mod.ts";
export default class UserController {
public async login(context: RouterContext) {
const { type, value } = (await context.request.body()) as BodyForm;
const params = await value;
const email = params.get("email");
const password = params.get("password");
console.log(email, password); // 2woongjae@gmail.com deno1234
if (email === null || password === null) {
context.response.status = 422;
context.response.body = { error: "email or password required" };
return;
}
const user = await getUserByEmail(email);
console.log(user);
const match = await bcrypt.compare(password, user.password);
console.log(match);
context.response.body = "login";
}
public logout(context: RouterContext) {
context.response.body = "logout";
}
}
➜ deno run --allow-net --allow-read --unstable main.ts
import {
create,
Header,
getNumericDate,
} from "https://deno.land/x/djwt@v2.2/mod.ts";
import { User } from "../models/User.ts";
const key = "markzzang";
const header: Header = {
alg: "HS256",
typ: "JWT",
};
export async function generate(user: User): Promise<string> {
return await create(
header,
{
iss: "mark",
exp: getNumericDate(10 * 60 * 60),
userId: user.userId,
email: user.email,
},
key
);
}
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
import { getUserByEmail } from "../models/User.ts";
import * as bcrypt from "https://deno.land/x/bcrypt@v0.2.4/mod.ts";
import { generate } from "../utils/token.ts";
export default class UserController {
public async login(context: RouterContext) {
const { type, value } = (await context.request.body()) as BodyForm;
const params = await value;
const email = params.get("email");
const password = params.get("password");
console.log(email, password); // 2woongjae@gmail.com deno1234
if (email === null || password === null) {
context.response.status = 422;
context.response.body = { error: "email or password required" };
return;
}
const user = await getUserByEmail(email);
console.log(user);
const match = await bcrypt.compare(password, user.password);
console.log(match);
if (match) {
context.response.body = { token: await generate(user) };
} else {
context.response.status = 400;
context.response.body = { error: "wrong password" };
}
}
public logout(context: RouterContext) {
context.response.body = "logout";
}
}
➜ curl --location --request POST 'localhost:5000/login' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'email=2woongjae@gmail.com' \
--data-urlencode 'password=deno1234'
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJtYXJrIiwiZXhwIjoxNjI2MTkxMzUxLCJ1c2VySWQiOiIzOTgxYzNjYS05ZGMwLTQyODctOTM5Zi03OWFlMjQzOGYyM2QiLCJlbWFpbCI6IjJ3b29uZ2phZUBnbWFpbC5jb20ifQ.TQVQNrDOTCcsr-6urqMa236bb9SJJYhqmYc_fU-EIn0"}%
➜ deno run -A --unstable https://deno.land/x/nessie/cli.ts make:migration create_books
Created migration /Users/mark/FastCampus/deno2021/books-api-deno/db/migrations/20210714233352_create_books.ts
import {
AbstractMigration,
Info,
ClientMySQL,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
export default class extends AbstractMigration<ClientMySQL> {
/** Runs on migrate */
async up(info: Info): Promise<void> {
await this.client.query(`
CREATE TABLE Books (
id int(11) NOT NULL AUTO_INCREMENT,
ownerId varchar(36) NOT NULL,
title varchar(255) NOT NULL,
message varchar(255) NOT NULL,
author varchar(255) NOT NULL,
url varchar(255) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp,
updated_at timestamp NOT NULL DEFAULT current_timestamp,
PRIMARY KEY (id)
);
`);
}
/** Runs on rollback */
async down(info: Info): Promise<void> {
await this.client.query("DROP TABLE IF EXISTS Books");
}
}
➜ deno run -A --unstable https://deno.land/x/nessie/cli.ts migrate
INFO connecting localhost:3306
INFO connected to localhost:3306
Starting migration of 1 files
----
Migrating 20210714233352_create_books.ts
Check file:///Users/mark/FastCampus/deno2021/books-api-deno/db/migrations/20210714233352_create_books.ts
Done in 8.40 seconds
----
Migrations completed in 8.40 seconds
INFO close connection
➜ deno install -qAf --unstable https://deno.land/x/denon/denon.ts
➜ denon run --allow-net --allow-read --unstable main.ts
import { RouterContext } from "https://deno.land/x/oak/mod.ts";
export default class BookController {
public getBooks(context: RouterContext) {
console.log(context.request.headers);
const authorization = context.request.headers.get("authorization");
console.log(authorization);
context.response.body = "getBooks";
}
}
import {
create,
Header,
getNumericDate,
verify,
Payload,
} from "https://deno.land/x/djwt@v2.2/mod.ts";
import { User } from "../models/User.ts";
const key = "markzzang";
const header: Header = {
alg: "HS256",
typ: "JWT",
};
export async function generate(user: User): Promise<string> {...}
export async function validate(token: string): Promise<Payload> {
return await verify(token, key, header.alg);
}
import client from "./config.ts";
export interface Book {
id: string;
ownerId: string;
title: string;
message: string;
author: string;
url: string;
created_at: Date;
updated_at: Date;
}
export async function getBooksByOwnerId(userId: string): Promise<Book[]> {
const { rows } = await client.execute(
`SELECT * FROM Books WHERE ownerId = '${userId}'`
);
if (rows === undefined) throw new Error();
return rows;
}
import { RouterContext } from "https://deno.land/x/oak/mod.ts";
import { validate } from "../utils/token.ts";
import { getBooksByOwnerId } from "../models/Book.ts";
export default class BookController {
public async getBooks(context: RouterContext) {
try {
const authorization = context.request.headers.get("authorization");
console.log(authorization);
if (authorization === null) {
throw new Error();
}
if (!authorization.startsWith("Bearer ")) {
throw new Error();
}
const token = authorization.replace("Bearer ", "");
console.log(token);
const payload = await validate(token);
console.log(payload);
const userId = payload.userId as string;
if (userId === undefined) {
throw new Error();
}
const books = await getBooksByOwnerId(userId);
context.response.body = books;
} catch (error) {
context.response.status = 401;
context.response.body = { error: "Unauthorized" };
}
}
}
import { config } from "https://deno.land/x/dotenv/mod.ts";
import { Application } from "https://deno.land/x/oak/mod.ts";
import router from "./routes.ts";
import notFound from "./not_found.ts";
const env = config();
const port = Number(env.PORT) || 5000;
const app = new Application();
app.use(async (context, next) => {
try {
await next();
} catch (error) {
context.response.status = error.status || 400;
context.response.body = { error: error.message };
}
});
app.use(router.routes());
app.use(notFound);
await app.listen({ port });
export class UnauthorizedError extends Error {
status = 401;
message = "Unauthorized Error";
}
import { RouterContext } from "https://deno.land/x/oak/mod.ts";
import { validate } from "../utils/token.ts";
import { getBooksByOwnerId } from "../models/Book.ts";
import { UnauthorizedError } from "../utils/error.ts";
export default class BookController {
public async getBooks(context: RouterContext) {
const authorization = context.request.headers.get("authorization");
if (authorization === null) {
throw new UnauthorizedError();
}
if (!authorization.startsWith("Bearer ")) {
throw new UnauthorizedError();
}
const token = authorization.replace("Bearer ", "");
const payload = await validate(token);
const userId = payload.userId as string;
if (userId === undefined) {
throw new UnauthorizedError();
}
const books = await getBooksByOwnerId(userId);
context.response.body = books;
}
}
import client from "./config.ts";
export type BookPostData = Pick<Book, "title" | "message" | "author" | "url">;
export async function getBooksByOwnerId(userId: string): Promise<Book[]> {...}
export async function createBook(
book: BookPostData,
ownerId: string
): Promise<void> {
await client.execute(
`INSERT INTO Books VALUES (DEFAULT, '${ownerId}', '${book.title}', '${book.message}', '${book.author}', '${book.url}', DEFAULT, DEFAULT)`
);
}
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
import { validate } from "../utils/token.ts";
import { getBooksByOwnerId, createBook } from "../models/Book.ts";
import { UnauthorizedError, ParameterRequired } from "../utils/error.ts";
export default class BookController {
public async createBook(context: RouterContext) {
const authorization = context.request.headers.get("authorization");
if (authorization === null) {
throw new UnauthorizedError();
}
if (!authorization.startsWith("Bearer ")) {
throw new UnauthorizedError();
}
const token = authorization.replace("Bearer ", "");
const payload = await validate(token);
const userId = payload.userId as string;
if (userId === undefined) {
throw new UnauthorizedError();
}
const { type, value } = (await context.request.body()) as BodyForm;
const params = await value;
const title = params.get("title");
const message = params.get("message");
const author = params.get("author");
const url = params.get("url");
if (title === null || message === null || author === null || url === null) {
throw new ParameterRequired();
}
await createBook({ title, message, author, url }, userId);
context.response.body = { success: true };
}
public async getBooks(context: RouterContext) {...}
}
export class UnauthorizedError extends Error {...}
export class ParameterRequired extends Error {
status = 422;
message = "All Paramets Required";
}
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
import { validate } from "../utils/token.ts";
import { getBooksByOwnerId, createBook, getBookById } from "../models/Book.ts";
import { UnauthorizedError, ParameterRequired } from "../utils/error.ts";
export default class BookController {
public async getBook(context: RouterContext) {
const bookId = Number(context.params.id) || null;
if (bookId === null) {
throw new ParameterRequired();
}
const authorization = context.request.headers.get("authorization");
if (authorization === null) {
throw new UnauthorizedError();
}
if (!authorization.startsWith("Bearer ")) {
throw new UnauthorizedError();
}
const token = authorization.replace("Bearer ", "");
const payload = await validate(token);
const userId = payload.userId as string;
if (userId === undefined) {
throw new UnauthorizedError();
}
const book = await getBookById(bookId, userId);
context.response.body = book;
}
}
export async function getBookById(id: number, ownerId: string): Promise<Book> {
const { rows } = await client.execute(
`SELECT * FROM Books WHERE ownerId = '${ownerId}' AND id = id`
);
if (rows === undefined) throw new Error();
if (rows.length !== 1) throw new Error();
return rows[0];
}
import { Middleware } from "https://deno.land/x/oak/mod.ts";
import { UnauthorizedError } from "../utils/error.ts";
import { validate } from "../utils/token.ts";
import { getUserByUserId, User } from "../models/User.ts";
const auth: Middleware<{ user: User }> = async (context, next) => {
const authorization = context.request.headers.get("authorization");
if (authorization === null) {
throw new UnauthorizedError();
}
if (!authorization.startsWith("Bearer ")) {
throw new UnauthorizedError();
}
const token = authorization.replace("Bearer ", "");
const payload = await validate(token);
const userId = payload.userId;
if (typeof userId !== "string") {
throw new UnauthorizedError();
}
const user = await getUserByUserId(userId);
context.state.user = user;
await next();
};
export default auth;
export async function getUserByUserId(userId: string): Promise<User> {
const { rows } = await client.execute(
`SELECT * FROM Users WHERE userId = '${userId}'`
);
if (rows === undefined) throw new Error();
if (rows.length !== 1) throw new Error();
return rows[0];
}
import { Router } from "https://deno.land/x/oak/mod.ts";
import UserController from "../controllers/UserController.ts";
import BookController from "../controllers/BookController.ts";
import auth from "./auth.ts";
const router = new Router();
const userController = new UserController();
const bookController = new BookController();
router
.post("/login", userController.login)
.delete("/logout", auth, userController.logout)
.post("/book", auth, bookController.createBook)
.get("/book", auth, bookController.getBooks)
.get("/book/:id", auth, bookController.getBook)
.patch("/book/:id", auth, bookController.updateBook)
.delete("/book/:id", auth, bookController.deleteBook);
export default router;
import { RouterContext, BodyForm } from "https://deno.land/x/oak/mod.ts";
import { getBooksByOwnerId, createBook, getBookById } from "../models/Book.ts";
import { ParameterRequired } from "../utils/error.ts";
import { User } from "../models/User.ts";
export default class BookController {
public async createBook(context: RouterContext<{}, { user: User }>) {
const { type, value } = (await context.request.body()) as BodyForm;
const params = await value;
const title = params.get("title");
const message = params.get("message");
const author = params.get("author");
const url = params.get("url");
if (title === null || message === null || author === null || url === null) {
throw new ParameterRequired();
}
await createBook(
{ title, message, author, url },
context.state.user.userId
);
context.response.body = { success: true };
}
public async getBooks(context: RouterContext<{}, { user: User }>) {
const books = await getBooksByOwnerId(context.state.user.userId);
context.response.body = books;
}
public async getBook(context: RouterContext<{ id: string }, { user: User }>) {
const bookId = Number(context.params.id) || null;
if (bookId === null) {
throw new ParameterRequired();
}
const book = await getBookById(bookId, context.state.user.userId);
context.response.body = book;
}
public updateBook(context: RouterContext<{ id: string }, { user: User }>) {...}
public deleteBook(context: RouterContext<{ id: string }, { user: User }>) {...}
}
export { config } from "https://deno.land/x/dotenv@v2.0.0/mod.ts";
export {
Application,
Router,
Context,
} from "https://deno.land/x/oak@v7.7.0/mod.ts";
export type {
Middleware,
RouterContext,
BodyForm,
} from "https://deno.land/x/oak@v7.7.0/mod.ts";
export {
ClientMySQL,
AbstractMigration,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
export type {
NessieConfig,
Info,
} from "https://deno.land/x/nessie@2.0.0/mod.ts";
export {
create,
getNumericDate,
verify,
} from "https://deno.land/x/djwt@v2.2/mod.ts";
export type { Header, Payload } from "https://deno.land/x/djwt@v2.2/mod.ts";
export { Client } from "https://deno.land/x/mysql@v2.9.0/mod.ts";
export { v4 } from "https://deno.land/std@0.100.0/uuid/mod.ts";
export * as bcrypt from "https://deno.land/x/bcrypt@v0.2.4/mod.ts";
import { config, Application } from "./deps.ts";
import errorHandler from "./middlewares/errorHandler.ts";
import router from "./middlewares/router.ts";
import notFound from "./middlewares/not_found.ts";
const env = config();
const port = Number(env.PORT) || 5000;
const app = new Application();
app.use(errorHandler);
app.use(router.routes());
app.use(notFound);
await app.listen({ port });
By Woongjae Lee
Deno 2021