示例
一系列的教程、示例、视频和指南,教你关于 Deno 运行时及如何与你喜欢的工具一起使用。
Can't find what you're looking for? Request a new guide
Featured
HTTP Server: Hello worldSpin up a web server with Deno.serve in a few lines. Writing testsUse the built-in test runner, no dependencies needed. Build a Next.js appRun a full-stack React framework on Deno. Connecting to databasesPostgres, MySQL, MongoDB, SQLite and more. Deploy with Deno DeployShip your app to the edge in minutes. Built in TypeScript supportRun TypeScript directly, with zero configuration.
按类型筛选:
326 items totalBasics Jump to heading
- Built in TypeScript supportDeno natively understands TypeScript code with no compiler to configure.
- Check if two values are deeply equalTwo objects with the same contents are not equal with the === operator, which compares references.
- Executable scripts使用 Deno 创建可执行脚本的指南。了解 hashbang、文件权限、跨平台兼容性,以及如何创建可直接从终端运行的命令行工具。
- Generating documentation with deno doc了解如何使用内置的 deno doc 命令为您的 Deno 项目生成专业文档。本教程涵盖 JSDoc 注释、HTML 输出、lint 检查以及文档编写最佳实践。
- Hello WorldThe one and only line in this program will print "Hello, World!" to the console.
- Import and export functionsTo build composable programs, it is necessary to be able to import and export functions from other modules.
- Initialize a project创建并构建新的 Deno 项目的指南。了解如何启动新项目、配置任务、管理依赖以及应用程序扩展的最佳实践。
- Run a script使用 Deno 创建和运行基础脚本的指南。学习如何编写和执行 JavaScript 和 TypeScript 代码,理解运行时环境,并开始了解 Deno 的基础概念。
- Sharing your local server with tunnel使用 --tunnel 选项立即暴露一个公共 URL
- Simple API server使用 Deno KV 和 Web 标准原语构建一个简单的链接缩短器 API,然后将其部署到 Deno Deploy。
- Simple file server使用 Deno 构建文件服务器的教程。学习如何处理 HTTP 请求、提供静态文件、实现流式响应,并使用标准库的文件服务器模块进行生产部署。
- Sleep and delay executionScripts often need to wait: between retries, while polling, or to pace requests.
- Top level awaitExample of how top-level await can be used by default in Deno.
- Update from CommonJS to ESM从 CommonJS 迁移到 ESM 模块的逐步指南。了解 import/export 语法变化、模块解析差异,以及如何在 Deno 中使用现代 JavaScript 特性。
Modules and package management Jump to heading
- Add and remove dependencies使用 deno add 和 deno remove 管理项目依赖:npm 和 JSR 包、版本固定、开发依赖,以及在 import map 中为包设置别名。
- Configure a monorepo with workspaces使用多个包搭建一个 Deno workspace:成员名称与导出、glob 模式、仅根目录选项、共享导入,以及通过 catalogs 集中管理依赖版本。
- Import modules from npmUse JavaScript modules from npm in your Deno programs with the "npm:" specifier in your imports.
- Lock dependencies with deno.lock使用 deno.lock 实现可复现安装:锁文件记录什么、如何审查锁文件差异、在 CI 中使用 --frozen 和 deno ci 冻结锁文件,以及如何重新生成或移动锁文件。
- Module MetadataDeno 中使用模块元数据的指南。了解 import.meta 属性、主模块检测、文件路径、URL 解析,以及如何在应用中访问模块上下文信息。
- Re-map import paths将 deno.json 中的 imports 字段用作导入映射:使用像 @/ 这样的路径别名指向 src/,为本地模块使用裸名称,并为传递性导入设置作用域覆盖。
- Run Deno in GitHub Actions为 Deno 项目设置 GitHub Actions 工作流:使用 setup-deno 安装 Deno、缓存依赖、运行 fmt、lint 和 test、使用冻结的 lockfile 进行安装,并在多个 Deno 版本之间进行测试。
- Run npm lifecycle scripts使用 deno approve-scripts 允许 Deno 中的 npm postinstall 和其他生命周期脚本,并使用 deno.json 中的 allowScripts 字段持久化这些批准。
- Use Deno in an existing Node.js project无需重写即可使用 Deno 运行现有的 Node.js 项目:从 package.json 安装,使用 deno task 运行 npm 脚本,使用 node: 内置模块,并逐步采用 Deno 的内置工具链。
- Use local and unpublished packages处理不在注册表中的代码:使用 links 字段链接本地包副本,直接从 HTTPS URL 导入(包括私有 GitHub 仓库),并了解 Deno 不支持哪些 specifier。
- Use Node.js built-in modulesDeno supports most built-in Node.js modules natively - you can include them in your code using "node:" specifiers in your imports.
- Use private npm registries将 Deno 配置为从私有注册表安装 npm 包:.npmrc 作用域注册表和认证令牌、NPM_CONFIG_REGISTRY 覆盖、DENO_AUTH_TOKENS,以及 Azure Artifacts 和 JFrog Artifactory 的实战配置。
Network Jump to heading
- Authentication with Auth.jsAuth.js is the most widely used authentication library for JavaScript.
- Build a chat app with WebSockets使用 Deno WebSockets 构建实时聊天应用的教程。学习如何使用 Oak 创建 WebSocket 服务器,处理多个客户端连接、管理状态,并使用 HTML、CSS 和 JavaScript 构建交互式聊天界面。
- Communicate over QUICQUIC is the transport protocol underneath HTTP/3.
- Connect two peers with WebTransportWebTransport is the web platform's API for low-latency, multiplexed communication over HTTP/3.
- Creating and verifying JWTThis example demonstrates how to create and verify a JSON Web Token (JWT) using the `jose` library in Deno.
- Download a file with progressStreaming a download straight to disk keeps memory flat no matter how big the file is.
- Email and password auth with Better AuthBetter Auth is a framework-agnostic, TypeScript-first auth library.
- Fetch over a Unix socketLocal services like the Docker daemon expose HTTP over a Unix domain socket instead of a TCP port.
- File Based Routing在 Deno 中实现基于文件的路由教程。学习如何创建类似 Next.js 的动态路由系统,处理 HTTP 方法,管理嵌套路由,并构建灵活的服务器架构。
- Find a free portTest servers and helper processes should not fight over hardcoded ports.
- Generate an RSS feedAn RSS feed is a small XML document that lets readers subscribe to a site.
- Generate sitemap.xml and robots.txtSearch engines discover pages through a sitemap and learn crawling rules from robots.txt.
- Hono HTTP serverAn example of a HTTP server that uses the Hono framework.
- HTTP requestsThis example demonstrates how to make a HTTP request to a server.
- HTTP server: Basic authenticationBasic authentication sends a username and password base64-encoded in the authorization header.
- HTTP server: Caching headersCache headers let clients skip downloads they already have.
- HTTP server: CookiesCookies carry state between requests in the cookie and set-cookie headers.
- HTTP server: CORSBrowsers block cross-origin requests unless the server opts in with CORS headers.
- HTTP server: CRUD with SQLite3An example of a HTTP server for CRUD routes with oak middleware framework and SQLite3 database.
- HTTP server: Graceful shutdownKilling a server mid-request drops connections and loses work.
- HTTP server: Health checksHealth endpoints let load balancers and orchestrators decide what to do with a process.
- HTTP Server: Hello worldAn example of a HTTP server that serves a "Hello World" message.
- HTTP server: Hot reloadRestarting a server by hand after every edit gets old fast.
- HTTP server: Node.js streamsCode ported from Node.js often produces Node streams: file streams, database cursors, archive generators.
- HTTP server: Paginating resultsAPIs that return lists need pagination so a single response stays small.
- HTTP server: Rate limitingA rate limiter protects a server from clients that send too many requests.
- HTTP server: Request timeoutsA handler that depends on a slow upstream can hold a connection open forever.
- HTTP server: RoutingAn example of a HTTP server that handles requests with different responses based on the incoming URL.
- HTTP server: Scaling across CPU coresA single process handles requests on one core.
- HTTP server: Server-sent eventsServer-sent events push updates from the server to the browser over a single long-lived HTTP response, with automatic reconnection built into the EventSource API.
- HTTP server: Serving filesAn example of a HTTP server that serves files.
- HTTP server: SessionsA session keeps a user logged in across requests.
- HTTP server: StreamingAn example HTTP server that streams a response back to the client.
- HTTP server: TLSDeno.serve speaks HTTPS when given a certificate and private key.
- HTTP server: Verifying webhook signaturesWebhook senders sign each delivery so receivers can prove the payload came from them and was not tampered with in transit.
- HTTP server: WebSocketsAn example of a HTTP server that handles websocket requests.
- Outbound WebSocketsOpening a WebSocket connection for real-time, bi-directional communication with Deno is very simple.
- Piping streamsDeno implements web-standard streams which comes with many advantages.
- Protect routes with JWT in HonoA common auth pattern is issuing a JSON Web Token at login and requiring it on protected routes.
- Proxy HTTP requestsA reverse proxy receives requests and forwards them to another server.
- Route fetch through an HTTP proxyDeno honors the HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables by default, for both module downloads and fetch, with no code changes.
- Running DNS queriesThere are some cases when running DNS queries is useful.
- Sign in with GitHub (OAuth)The OAuth authorization code flow lets users sign in with an existing account.
- TCP connector: PingAn example of connecting to a TCP server on localhost and writing a 'ping' message to the server.
- TCP Echo ServerAn echo server is a simple network application that listens for incoming connections and requests, and then repeats back any data it receives from clients.
- TCP listener: PingAn example of a TCP listener on localhost that will log the message if written to and close the connection if connected to.
- TCP/TLS connector: PingAn example of connecting to a TCP server using TLS on localhost and writing a 'ping' message to the server.
- TCP/TLS listener: PingAn example of a TCP listener using TLS on localhost that will log the message if written to and close the connection if connected to.
- Two-way streaming with WebSocketStreamWebSocketStream is a promise-based alternative to the event-based WebSocket API.
- UDP connector: PingAn example of writing a 'ping' message to a UDP server on localhost.
- UDP listener: PingAn example of a UDP listener on localhost that will log the message if written to and close the connection if connected to.
- Upgrade a TCP connection to TLS (STARTTLS)Some protocols start as plaintext and negotiate encryption mid-connection instead of connecting over TLS from the start.
- WebSocket server: Broadcasting messagesChat rooms, live dashboards, and multiplayer games all need one thing: deliver a message from one client to all the others.
- WebSocket server: Per-socket stateMost WebSocket servers need to know who each socket belongs to: a username, a room, a session.
File system Jump to heading
- Checking for file existenceWhen creating files it can be useful to first ensure that such a file doesn't already exist.
- Convert between file URLs and pathsModules are identified by URLs in Deno, while file system APIs take paths.
- Copy a fileCopying a file is a single call in Deno.
- Create and extract tar archivesA tar archive bundles many files and directories into a single file, usually compressed with gzip to produce the familiar .tar.gz format.
- Create hard linksA hard link is a second name for the same file.
- Creating & removing directoriesCreating and removing directories is a common task.
- Creating & resolving symlinksCreating and resolving symlink is a common task.
- Deleting filesRemoving files and directories is a common task.
- File system events使用 Deno 监控文件系统更改的教程。了解如何监视目录以捕获文件修改、处理更改事件,并理解在 Linux、macOS 和 Windows 上的特定平台行为。
- Find files with glob patternsGlob patterns describe sets of file paths in one compact string, with * matching within a path segment and ** matching across directories.
- Get the MIME type of a fileServing a file over HTTP needs a content type header.
- Lock files across processesWhen two processes write the same file at the same time, the result is a mess.
- Moving/Renaming filesAn example of how to move and rename files and directories in Deno.
- Path operationsMany applications need to manipulate file paths in one way or another.
- Read and change file metadataEvery file carries metadata besides its contents: size, timestamps, type and permissions.
- Reading filesMany applications need to read files from disk.
- Streaming file operationsSometimes we need more granular control over file operations.
- Temporary files & directoriesTemporary files and directories are used to store data that is not intended to be permanent.
- Truncate a fileTruncating sets a file to an exact length without rewriting its contents.
- Unix catIn Unix, the `cat` command is a utility that reads files and writes them to standard output.
- Walking directoriesWhen doing something like filesystem routing, it is useful to be able to walk down a directory to visit files.
- Watching the filesystemWhen creating frameworks or CLI tools, it is often necessary to watch the filesystem for changes.
- Write a file incrementallyWriting a file all at once is fine until the data is large or arrives in pieces, like a download or a log.
- Writing filesMany applications need to write files to disk.
System Jump to heading
- Call C functions with FFIThe Foreign Function Interface lets Deno call functions in native shared libraries directly, with no glue code or build step.
- Collecting output from subprocessesWe don't often write programs in isolation.
- Communicate with a child process over IPCPipes carry bytes, but coordinating with a worker process is easier with structured messages.
- Create a subprocessDeno 中使用子进程的指南。了解如何生成进程、处理输入/输出流、管理进程生命周期,并安全地实现进程间通信模式。
- Detect a TTY and get terminal sizeA program can check whether it is talking to a real terminal or to a pipe.
- Environment variablesEnvironment variables can be used to configure the behavior of a program, or pass data from one program to another.
- Find an executable on the PATHBefore spawning a tool like git or ffmpeg, it is useful to know whether it is installed and where.
- Get operating system informationScripts often need to know what system they are running on, for example to pick a platform specific binary or to include host details in logs.
- Handle OS signals关于在 Deno 中处理操作系统信号的教程。学习如何捕获 SIGINT 和 SIGBREAK 事件、管理信号监听器,以及在应用程序中实现优雅关闭处理程序。
- List network interfacesDeno.networkInterfaces lists every network address of the machine.
- Listen for OS signalsYou can listen for OS signals using the `Deno.addSignalListener` function.
- Pipe data into a subprocessMany command line tools read their input from stdin.
- Process informationAn example of how to access the current process ID and parent process ID.
- Read from stdinCommand line tools that work in pipelines read their input from stdin.
- Read input line by line with node:readlineThe node:readline module reads a stream one line at a time, no matter how the bytes are chunked, and it powers interactive prompts in many Node.js programs.
- Reading system metricsThis example demonstrates how to use Deno's built-in methods to read system metrics such as memory information, load averages and memory usage.
- Run a subprocess with custom env and cwdA subprocess normally inherits the environment variables and working directory of its parent.
- Set and read process exit codesThe exit code is how a program reports success or failure to the shell, where zero means success and anything else means failure.
- Set the time zoneDate, Intl, and Temporal all format times in the process time zone, which defaults to the operating system setting.
- Subprocesses: SpawningFor more complex usecases, we don't simply want the output of some command.
- Use EventEmitter from node:eventsEventEmitter is the classic Node.js building block for things that emit named events, and countless npm packages hand you one.
- Use worker_threads in DenoDeno supports the node:worker_threads module for moving work off the main thread.
- Write to stdoutconsole.log is fine for debugging, but command line tools often need precise control over standard output: no forced newline, raw bytes, or piping a whole stream.
Web standard APIs Jump to heading
- Better debugging with the console APIDeno 中高级控制台调试的深入指南。了解 console.table、计时器、计数器、追踪器,以及如何在基础日志之外充分利用完整的 console API,以实现更好的调试工作流。
- Build and send forms with FormDataFormData collects key and value pairs, including files, and fetch knows how to send it as a multipart request.
- Cache HTTP responses with the Web Cache APIDeno implements the Web Cache API from service workers.
- Cancel async work with AbortControllerAbortController produces an AbortSignal that can cancel fetch requests, remove event listeners, and stop any code that checks the signal.
- Communicate between workers with BroadcastChannelBroadcastChannel is a named bus.
- Create and dispatch custom eventsEventTarget is the eventing system behind the DOM, and it works as a base class for your own types.
- Deep clone objects with structuredClonestructuredClone deep copies a value, so changes to the copy never leak back into the original.
- Distribute work across a worker poolA single web worker moves heavy computation off the main thread, but a pool of workers uses every CPU core.
- Escape an HTML stringInterpolating user input into HTML without escaping it opens the door to cross-site scripting.
- Extract links and metadata from HTMLScrapers, link checkers, and preview cards all start the same way: fetch a page and pull data out of its HTML.
- Fetch and stream data关于在 Deno 中处理网络请求的教程。了解如何使用 fetch API 进行 HTTP 请求、处理响应、实现数据流式传输,以及管理文件上传和下载。
- Format dates for any localeIntl.DateTimeFormat turns a Date into text for any locale and time zone.
- Format numbers and currenciesIntl.NumberFormat formats numbers for any locale and style.
- Format relative timeIntl.RelativeTimeFormat produces phrases like 3 days ago or in 2 months for any locale.
- Logging with colorsMost modern terminals can display program logs in colors and with text decorations.
- Manipulating & parsing URLsURL is the web standard interface to parse and manipulate URLs.
- Match URLs with URLPatternURLPattern matches URLs against route-style patterns and extracts the dynamic parts.
- Measure performance with marks and measuresThe performance API measures elapsed time with sub-millisecond precision.
- Parse and format datesEveryday date work is parsing a value, formatting it for people, and doing arithmetic on it.
- Pluralize and format listsHand-rolled pluralization like adding an s breaks as soon as you leave English.
- Run a compute shader with WebGPUWebGPU gives JavaScript direct access to the GPU, and unlike WebGL it is not limited to graphics: compute shaders run arbitrary parallel computation.
- Set a timeout on fetchfetch has no timeout option, but it accepts an AbortSignal, and AbortSignal.timeout builds one that aborts after a given number of milliseconds.
- Set timeout and intervalsTimers are used to schedule functions to happen at a later time.
- Split text by words, sentences, and graphemesSplitting text with split or slice breaks on punctuation, emoji, and languages that do not use spaces.
- Temporal APIAn example of using the Temporal API to work with dates, times, and timestamps.
- Transform data with TransformStreamA TransformStream sits in the middle of a stream pipeline and rewrites chunks as they pass through.
- Web assemblyWebAssembly is a binary format for describing a program's data and instructions.
- Web workersWorkers are the only way of running javascript off of the main thread.
Standard library Jump to heading
- Add a timeout to any promiseA promise has no built-in time limit, so a stalled request can hang a program forever.
- Convert string caseIdentifiers, file names, CSS classes, and database columns all expect different casing conventions.
- Debounce a functionA debounced function waits until calls stop arriving before it runs.
- Escape text for regular expressionsBuilding a RegExp from user input is dangerous, because characters like parentheses and dots have special meaning in patterns.
- Exponential backoffExponential backoff is a technique used in computer systems to handle retries and avoid overwhelming services.
- Format bytes and durations for humansRaw numbers like 1536 bytes or 97000 milliseconds are hard to read in logs and user interfaces.
- Generate seeded random numbersMath.random gives you no way to set a seed, so test runs and simulations that need reproducible randomness cannot use it.
- Memoize an expensive functionMemoization caches the result of a function call so repeated calls with the same arguments return instantly.
- Parse and compare semver versionsVersion strings cannot be compared as plain text, because "1.10.0" sorts before "1.2.0" alphabetically.
- Run async tasks with a concurrency limitFiring hundreds of requests at once can overwhelm a server or hit rate limits.
- Structured loggingThe @std/log package routes log records through configurable handlers with severity levels.
- User Data Processing with Deno CollectionsDemonstrates using Deno's @std/collections library for processing user data.
Encoding Jump to heading
- Compress and decompress dataCompressing data before storing or sending it saves space and bandwidth.
- Compress data with node:zlibThe node:zlib module is built into Deno and offers more codecs and options than the web standard streams, including brotli and synchronous one-shot helpers.
- Convert a BlobBlobs show up whenever you handle files or multipart form data, since an uploaded File is a Blob too.
- Convert a Buffer (node:buffer)Node.js APIs and many npm packages produce Buffer objects.
- Convert a Node.js ReadableNode.js APIs and npm packages often return a Node.js Readable rather than a web ReadableStream.
- Convert a ReadableStreamNetwork responses, file handles, and subprocess output all hand you a ReadableStream.
- Convert a string to bytes and backHashing, file writes, and network protocols all want bytes, not strings.
- Convert a Uint8ArrayUint8Array is the workhorse binary type in Deno: file reads, network payloads, and hashes all produce or consume it.
- Convert an ArrayBufferAn ArrayBuffer is a chunk of raw memory with no read or write interface of its own.
- Encode and decode CBORCBOR is a binary serialization format standardized as RFC 8949.
- Encode and decode MessagePackMessagePack is a binary serialization format with the same data model as JSON.
- Extract front matter from markdownFront matter is a metadata block at the top of a markdown file, fenced by --- lines and usually written in YAML.
- Hex and base64 encodingBinary data often needs to travel as text, in URLs, JSON, or HTTP headers.
- Importing bytesBinary files can be imported in JS and TS files using the `import` keyword.
- Importing JSONJSON files can be imported in JS and TS files using the `import` keyword.
- Importing textText files can be imported in JS and TS files using the `import` keyword.
- Manipulating byte arraysWhen working with lower-level data we often deal with byte arrays in the form of Uint8Arrays.
- Parse and generate XMLThe @libs/xml package on JSR converts XML in both directions: XML text to plain JavaScript objects and back.
- Parse large CSV files as streamsReading a whole CSV file into memory does not work once the file grows to gigabytes.
- Parsing and serializing CSVCSV is a data serialization format that is designed to be portable for table-like applications.
- Parsing and serializing INIINI is a plain text configuration format built from key value pairs that can be grouped into sections.
- Parsing and serializing JSONJSON is a widely used data interchange format.
- Parsing and serializing TOMLTOML is a widely used configuration language designed to be feature-rich and intuitive to write.
- Parsing and serializing YAMLYAML is a widely used data serialization language designed to be easily human readable and writeable.
- Parsing JSONCJSONC is JSON extended with comments and trailing commas, which makes it a friendlier format for configuration files that humans edit.
- Stream JSON Lines dataJSON Lines, also called NDJSON, stores one JSON value per line.
CLI Jump to heading
- Build a CLI with subcommandsTools like git and deno itself take a subcommand first and flags after it.
- Bundle code with Deno.bundleDeno.bundle compiles a module graph into a single JavaScript file, resolving and inlining all imports, including jsr: and npm: packages.
- Command line argumentsCommand line arguments are often used to pass configuration options to a program.
- Compile a script into an executableThe deno compile subcommand turns a script and all of its dependencies into a single self-contained binary.
- Control the terminal with ANSI escape codesTerminals interpret special byte sequences, called ANSI escape codes, as commands: change the text color, erase a line, move or hide the cursor.
- Debugging with Chrome DevTools
- Find and update outdated dependenciesDependencies pinned months ago quietly fall behind.
- Getting the Deno versionHow to examine the version of Deno being used.
- Input promptsPrompts are used to ask the user for input or feedback on actions.
- Inspect memory with heap snapshotsWhen memory keeps growing, a heap snapshot shows what is holding it: a full dump of every live object, inspectable in Chrome DevTools.
- Permission managementThere are times where depending on the state of permissions granted to a process, we want to do different things.
- Rich output in Jupyter notebooksDeno ships a Jupyter kernel, so notebooks can run TypeScript with full access to the Deno and web APIs.
- Show progress bars and spinnersLong-running command line tools feel broken when they print nothing.
- Write benchmarks with Deno.benchDeno has a built-in benchmark runner.
Cryptography Jump to heading
- AES Encryption and DecryptionThis example demonstrates AES encryption and decryption using Deno's built-in SubtleCrypto API.
- Compare secrets in constant timeAn ordinary comparison like a === b returns as soon as the first byte differs, so a correct first byte takes measurably longer to reject than a wrong one.
- Derive encryption keys from passwordsA password is not an encryption key: it is short, low entropy, and the wrong size for AES.
- Generate secure random valuesSession tokens, password reset links, and API keys must be impossible to guess.
- Generating & validating UUIDsUUIDs (universally unique identifier) can be used to uniquely identify some object or data.
- Hash and sign with node:cryptoDeno supports the node:crypto module so that npm packages relying on it work out of the box.
- Hash large files with streamsThe Web Crypto digest function takes a single buffer, so hashing a file with it means reading the whole file into memory first.
- HashingHashing data is a common operation that is facilitated through Deno's support for the Web Crypto API.
- Hashing and verifying passwordsPasswords must never be stored in plain text, and a plain digest like SHA-256 is too fast to resist brute force.
- HMAC Generation and VerificationThis example demonstrates how to generate and verify an HMAC (Hash-based Message Authentication Code) using Deno's built-in SubtleCrypto API with the SHA-256 hash function.
- RSASSA-PKCS1-v1_5 Signature and VerificationThis example demonstrates RSA signature and verification using Deno's built-in SubtleCrypto API.
- Sign and verify data with ECDSAA digital signature proves that a message was produced by the holder of a private key and was not modified in transit.
- ULIDOne common need for distributed systems are identifiers.
Testing Jump to heading
- Basics of testing了解测试设置与结构、断言、异步测试、mock、测试夹具和代码覆盖率等关键概念
- BDD testing使用 Deno 标准库的 BDD 模块实现行为驱动开发。创建可读性强、组织良好的测试,并配合有效的断言。
- Filtering and controlling test runsThe test runner has flags for the everyday loops: run one test by name, stop at the first failure, rerun on save, and spread test files across CPU cores.
- Mocking and test doubles
- Skipping and focusing testsSometimes a test should not run: it is half-written, broken on one platform, or you want to focus on a single failing case.
- Snapshot testing
- Spy functionsA function spy allow us to assert that a function was called with the correct arguments and a specific number of times.
- Testing web applications使用 Deno 测试 Web 应用程序的综合指南
- Use Testing Library with Deno使用 @testing-library/dom 和 happy-dom 在 deno test 中测试 DOM 行为:通过角色和文本进行查询、模拟事件,以及此设置所需的权限。
- Writing testsOne of the most common tasks in developing software is writing tests for existing code.
Web frameworks and libraries Jump to heading
- Accept payments with Stripe CheckoutStripe Checkout hosts the payment page for you.
- Build a Fresh app使用 Fresh 和 Deno 构建全栈应用的完整指南。学习如何搭建项目、使用岛屿架构实现服务端渲染、添加 API 路由,并部署你的 TypeScript 应用。
- Build a Next.js app使用 Deno 构建 Next.js 应用的分步指南。学习如何设置项目、创建 API 路由、实现服务器端渲染,并构建一个全栈 TypeScript 应用。
- Build a Nuxt app with Deno使用 Deno 构建 Nuxt 应用的循序渐进指南。学习如何创建完整的全栈 Vue.js 应用、实现服务端渲染、添加 Tailwind 样式,并部署你的应用。
- Build a Qwik app with Deno使用 Deno 构建 Qwik 应用的循序渐进指南。了解可恢复性(resumability)、服务器端渲染(server-side rendering)、路由处理,以及如何默认实现零客户端 JavaScript 的方式来创建快速、现代的 Web 应用。
- Build a React App使用 Deno 和 Vite 构建 React 应用的完整指南。了解如何设置项目、实现路由、添加 API 端点,以及部署你的全栈 TypeScript 应用。
- Build a SolidJS app使用 Deno 构建一个 SolidJS 应用。了解如何搭建项目、实现响应式组件、处理路由、使用 Hono 创建 API 端点,并构建一个全栈 TypeScript 应用。
- Build a Svelte app一个使用 Deno 构建 SvelteKit 应用程序的教程。学习如何设置 SvelteKit 项目、实现基于文件的路由、使用 load 函数管理状态,以及创建一个全栈 TypeScript 应用程序。
- Build a Tanstack app使用 Tanstack 和 Deno 构建应用的完整指南。学习如何实现 Query 进行数据获取,Router 进行导航,管理服务器状态,并创建类型安全的全栈应用。
- Build a Typesafe API with tRPC and Deno学习使用 tRPC 和 Deno 构建类型安全的 API。了解如何设置端点、实现 RPC 过程、处理数据校验,并创建高效的客户端-服务器应用。
- Build a Vue app使用 Deno 构建 Vue.js 应用程序的教程。学习如何设置 Vite 项目、实现组件架构、添加路由、管理状态以及创建一个全栈 TypeScript 应用程序。
- Build a word finder app本教程介绍如何使用 Deno 创建一个单词搜索应用。学习如何构建 Web 服务器、实现模式匹配、处理 HTTP 请求,并使用 Oak 框架创建交互式 Web 界面。
- Build an Astro site with Deno使用 Astro 和 Deno 构建 Web 应用的分步教程。了解如何搭建项目脚手架、创建动态页面、实现 SSR,并使用 Deno 的 Node.js 兼容性部署你的 Astro 站点。
- Generate a PDFThe pdf-lib package creates and edits PDF documents in pure JavaScript, so it runs anywhere Deno does, including Deno Deploy.
- Generate a QR codeA QR code encodes a short piece of text, usually a URL, as a scannable image.
- How to use Apollo with Deno关于将 Apollo GraphQL 集成到 Deno 的逐步教程。学习如何设置 Apollo Server、定义 schema、实现 resolvers,并使用 TypeScript 构建一个完整的 GraphQL API。
- HTTP server file uploadAn example HTTP server that provides sending and receiving of a file upload.
- Render HTML templates with EtaWhen JSX is more than you need, a string template engine renders HTML from plain templates and data.
- Render markdown to HTMLThe @deno/gfm module renders GitHub Flavored Markdown to HTML, with the same tables, task lists, and syntax highlighting you see on GitHub.
- Resize and convert imagessharp is the standard high-performance image processing library, and it runs in Deno through npm.
- Send email with ResendTransactional email, like sign-up confirmations and receipts, is a common need.
- Send email with SendGridSendGrid is a widely used transactional email service.
- Upload files to S3-compatible storageThe AWS SDK works with any S3-compatible store, including Amazon S3 and Cloudflare R2.
- Use Express with Deno使用 Deno 配合 Express.js 的循序渐进指南。了解如何设置 Express 服务器、配置路由、处理中间件,并使用 Deno 的 Node.js 兼容功能构建 REST API。
- Use Vite with Deno关于使用 Vite 和 Deno 构建前端应用的分步教程。了解如何搭建项目、安装依赖、运行带热模块替换的开发服务器,以及构建用于生产环境的版本。
Databases Jump to heading
- Drizzle使用 Drizzle ORM 和 Deno 构建数据库应用的分步指南。了解模式管理、类型安全查询、PostgreSQL 集成、迁移,以及如何实现 CRUD 操作。
- DuckDBUsing Deno with DuckDB, you can connect to memory or a persistent database with a filename.
- How to use Redis with Deno使用 Deno 搭配 Redis 的分步指南。学习如何设置缓存、实现消息代理、处理数据流,并使用 Redis 的内存数据存储来优化你的应用。
- MongoDBUsing the Deno MongoDB client, you can connect to a Mongo database running anywhere.
- Mongoose使用 Deno 搭配 Mongoose 的一步步指南。了解如何设置 MongoDB 连接、创建模式、实现数据模型,并使用 Mongoose 基于模式的建模执行 CRUD 操作。
- MySQL逐步指南:在 Deno 中使用 MySQL2。学习如何设置数据库连接、执行查询、处理事务,以及使用 MySQL 的 Node.js 驱动构建数据驱动应用。
- OverviewDeno 中数据库连接指南。学习如何使用 MySQL、PostgreSQL、MongoDB、SQLite、Firebase、Supabase 以及流行的 ORM,通过 TypeScript 构建数据驱动的应用程序。
- PlanetScale使用 Deno 搭配 Planetscale 的分步指南。了解如何设置无服务器 MySQL 数据库、管理连接、执行查询,并使用 Planetscale 的开发者友好型平台构建可扩展应用。
- PostgresUsing the npm Postgres client, you can connect to a Postgres database running anywhere.
- Prisma使用 Deno,借助 Prisma 和 Oak 构建 RESTful API 指南。学习如何设置数据库模式、生成客户端、实现 CRUD 操作,并以良好的类型安全部署你的 API。
- Redis quick startUsing the npm:redis module (node-redis), you can connect to a Redis database running anywhere.
- SQLiteUsing the `node:sqlite` module, you can connect to an SQLite3 database stored locally and perform basic database operations.
- SupabaseConnect to a Supabase database with the supabase-js library.
Deno KV and scheduling Jump to heading
- Atomic transactions in Deno KVDeno KV transactions group reads and writes so they either all happen or none do, with optimistic concurrency: a transaction only commits if the values it read have not changed in the meantime.
- Deno CronDeno Cron is a cron task scheduler built into the Deno runtime and works with zero configuration on Deno Deploy.
- Deno KV watchDeno KV watch allows you to detect changes to your KV database, making it easier to build real-time applications, newsfeeds, chat, and more.
- Deno KV: Key/Value databaseDeno KV is a key/value database built in to the Deno runtime, and works with zero configuration on Deno Deploy.
- Deno queuesDeno Queues, built on Deno KV, allow you to offload parts of your application or schedule work for the future to run asynchronously.
AI Jump to heading
- Build an agent with OpenAI function callingFunction calling lets the model call functions you define and act on the results.
- Build an agent with tool useTool use lets Claude call functions you define and act on the results.
- Build an MCP serverThe Model Context Protocol (MCP) is the standard way to expose tools and data to AI assistants like Claude.
- Connect to an MCP server from a clientThe other side of the Model Context Protocol: a client connects to a server, discovers the tools it advertises, and calls them.
- Connect to Claude (Anthropic API)The official Anthropic SDK runs in Deno straight from npm.
- Connect to OpenAI - Chat completionThis example demonstrates how to interact with OpenAI's chat completions API using Deno, where we send a user prompt and receive a response from the GPT-4 model.
- Get structured JSON output from ClaudeWhen you need machine-readable output, constrain Claude's response to a JSON schema with output_config.format.
- Get structured JSON output from OpenAIWhen you need machine-readable output, constrain the response to a JSON schema with response_format.
- LLM Chat app学习如何将大型语言模型(LLM)与 Deno 集成,使用 OpenAI 或 Anthropic API 创建一个交互式角色扮演聊天应用,其中包含 AI 角色。
- RAG: ground an OpenAI answer in your documentsRetrieval-augmented generation grounds an answer in your own data.
- RAG: ground Claude's answer in your documentsRetrieval-augmented generation grounds an answer in your own data.
- Stream a chat response from OpenAIThe official OpenAI SDK runs in Deno straight from npm.
- Stream a Claude response to the browserA chat UI needs tokens to appear as the model produces them.
- Stream an OpenAI response to the browserA chat UI needs tokens to appear as the model produces them.
Deploying Deno projects Jump to heading
- AWS ECS Fargate将 Deno 应用部署到 AWS ECS Fargate 的分步教程。学习如何将 Deno 应用容器化、将镜像推送到 Amazon ECR,并在负载均衡器后面作为无服务器 Fargate 服务运行它。
- AWS LambdaStep-by-step tutorial on deploying Deno applications to AWS Lambda.
- AWS Lightsail关于将 Deno 应用部署到 AWS Lightsail 的逐步教程。了解 Docker 容器、GitHub Actions 自动化、持续部署,以及如何为 Deno 应用设置具有成本效益的云托管。
- Cloudflare workers逐步教程:将 Deno 函数部署到 Cloudflare Workers。了解如何配置 denoflare、创建 worker 模块、进行本地测试,并将代码部署到 Cloudflare 的全球边缘网络。
- Cloudflare workers with wrangler了解如何使用 Wrangler 构建并将 Deno 应用部署到 Cloudflare Workers
- Connecting to a database both locally and on Deno Deploy使用 Deno Deploy 和 Deno 的隧道功能将 Postgres 数据库连接到你的本地开发服务器
- Deploy with Deno Deploy一步一步教程:将你的第一个 Deno 应用部署到 Deno Deploy。
- Deploy with the deploy command使用 deno deploy CLI 命令创建并将你的第一个应用部署到 Deno Deploy 的分步教程。
- Digital Ocean分步骤指南:在 Digital Ocean 上部署 Deno 应用。了解 Docker 容器化、GitHub Actions 自动化、容器注册表以及如何设置持续部署工作流。
- Google Cloud Run一步步指南,教您在 Google Cloud Run 上部署 Deno 应用程序。了解 Docker 容器化、Artifact Registry 配置、GitHub Actions 自动化,以及如何设置到 Google Cloud 的持续部署。
- Kinsta在 Kinsta 上部署 Deno 应用的循序渐进指南。了解如何配置 package.json、处理环境变量、设置 Git 部署,以及使用 Kinsta 的应用托管平台。
- Migrating a custom domain to Deno Deploy了解如何将自定义域从 Deploy Classic 迁移到 Deno Deploy
- Use Deno in Docker
OpenTelemetry Jump to heading
- Basic OpenTelemetry setup在 Deno 应用中设置基础的 OpenTelemetry 监测。本教程涵盖创建一个带自定义指标和跟踪的简单 HTTP 服务器,并查看遥测数据。
- Export telemetry to Grafana使用 OpenTelemetry 和 Grafana 导出遥测数据的完整指南。了解如何配置采集器、可视化追踪数据以及监控应用性能。
- Export telemetry to Honeycomb使用 OpenTelemetry 和 Honeycomb.io 导出遥测数据的完整指南。了解如何配置收集器、可视化追踪并监控应用性能。
- Export telemetry to Hyperdx使用 OpenTelemetry 和 HyperDX 导出遥测数据的完整指南。了解如何配置采集器,并有效地可视化追踪、日志、指标以及调试分布式应用程序。
- OpenTelemetry with Deno Deploy关于为您的 Deno Deploy 应用添加自定义 OpenTelemetry 仪表的分步教程。
- Span propagation在 Deno 应用中实现端到端分布式追踪,并自动进行上下文传播。本教程涵盖创建带追踪的服务、自动传播追踪上下文,以及可视化分布式追踪。
- View telemetry data for your local application使用 Deno 的隧道功能,从你的本地开发服务器发送遥测
Deno Sandbox Jump to heading
- Add read-write volumes to your Sandbox为你的 Deno 沙箱添加可读写的块存储。
- Boot a Python environment with snapshots创建一个沙箱,预加载 Python + 科学计算包,对其进行快照,并启动无需额外配置的沙箱来运行一个曼德尔布罗特探索器。
- Boot instantly with snapshots使用只读镜像来创建隔离且可重复的环境。
- Command cancellation了解如何在沙箱中取消命令。
- Configure sandbox memory了解如何配置分配给沙箱的内存
- Control sandbox timeout了解如何使用 timeout 选项控制沙箱的存活时长。
- Error handling了解如何在沙箱中处理错误。
- Evaluating JavaScriptYou can evaluate JavaScript code in a sandbox using the `eval` function.
- Interactive JavaScript REPL了解如何在沙箱中提供一个交互式 Deno REPL。
- Provide a VSCode instance in a sandbox了解如何在沙箱中提供一个 VSCode 实例。
- Provide SSH access to a sandbox了解如何为沙箱提供 SSH 访问权限。
- Run AI generated codeDeno Deploy's Sandbox API lets you create secure microVMs to run untrusted code safely.
- Serve a web framework创建一个 package.json,安装依赖,运行一个 Web 框架(Express),并从沙箱中将其公开到外部
- Set and get environment variables了解如何在沙箱中设置和获取环境变量。
- Spawn a subprocess了解如何生成子进程,并在沙箱中获取缓冲输出。
- Stream output to a local file了解如何在沙箱中将输出流式传输到本地文件。
- Streaming access string and binary output了解如何从沙箱中的命令流式获取字符串和二进制输出。
- Upload files and directories to a sandbox了解如何将文件和目录上传到沙箱。
- Use template literals with variable interpolation了解如何在沙箱中使用带变量插值的模板字面量命令。
Oops! You've filtered everything
Maybe remove a filter to see some examples?

