Ende examples and tutorials
A collection of walkthrough tutorials, examples, videos and guides to teach you about the Ende runtime and how to use it with your favorite tools.
Featured
- HTTP Server: Hello world (example): Spin up a web server with Ende.serve in a few lines.
- Writing tests (example): Use the built-in test runner, no dependencies needed.
- Connecting to databases (tutorial): Postgres, MySQL, MongoDB, SQLite and more.
- Built in TypeScript support (video): Run TypeScript directly, with zero configuration.
Basics
- Built in TypeScript support (example): Ende natively understands TypeScript code with no compiler to configure.
- Check if two values are deeply equal (example): Two objects with the same contents are not equal with the === operator, which compares references.
- Executable scripts (tutorial): Guide to creating executable scripts with Ende.
- Generating documentation with ende doc (tutorial): Learn how to generate professional documentation for your Ende projects using the built-in ende doc command.
- Hello World (example): " to the console.
- Import and export functions (example): To build composable programs, it is necessary to be able to import and export functions from other modules.
- Initialize a project (tutorial): Guide to creating and structuring new Ende projects.
- Run a script (tutorial): A guide to creating and running basic scripts with Ende.
- Simple file server (tutorial): Tutorial on building a file server with Ende.
- Sleep and delay execution (example): Scripts often need to wait: between retries, while polling, or to pace requests.
Modules and package management
- Add and remove dependencies (tutorial): Manage project dependencies with ende add and ende remove: JSR packages, version pinning, and aliasing packages in your import map.
- Configure a monorepo with workspaces (tutorial): Set up an Ende workspace with multiple packages: member names and exports, glob patterns, root-only options, and shared imports.
- Lock dependencies with ende.lock (tutorial): lock for reproducible installs: what the lockfile records, reviewing lockfile diffs, frozen lockfiles for CI with --frozen-lockfile and ende ci, and regenerating or relocating the lockfile.
- Module Metadata (tutorial): A guide to working with module metadata in Ende.
- Re-map import paths (tutorial): json as an import map: path aliases like @/ for src/, bare names for local modules, and scoped overrides for transitive imports.
- Run Ende in GitHub Actions (tutorial): Set up a GitHub Actions workflow for an Ende project: install Ende with its install script, run fmt, lint and test, install with a frozen lockfile, and pin an Ende version.
- Use local and unpublished packages (tutorial): Work with code that isn’t on a registry: link a local package copy with the links field, import straight from HTTPS URLs including private GitHub repos, and know which specifiers Ende does not support.
Network
- Communicate over QUIC (example): QUIC is the transport protocol underneath HTTP/3.
- Connect two peers with WebTransport (example): WebTransport is the web platform’s API for low-latency, multiplexed communication over HTTP/3.
- Download a file with progress (example): Streaming a download straight to disk keeps memory flat no matter how big the file is.
- Fetch over a Unix socket (example): Local services like the Docker daemon expose HTTP over a Unix domain socket instead of a TCP port.
- File Based Routing (tutorial): Tutorial on implementing file-based routing in Ende.
- Find a free port (example): Test servers and helper processes should not fight over hardcoded ports.
- Generate an RSS feed (example): An RSS feed is a small XML document that lets readers subscribe to a site.
- Generate sitemap.xml and robots.txt (example): txt.
- Hono HTTP server (example): An example of an HTTP server that uses the Hono framework.
- HTTP requests (example): This example demonstrates how to make an HTTP request to a server.
- HTTP server: Basic authentication (example): Basic authentication sends a username and password base64-encoded in the authorization header.
- HTTP server: Caching headers (example): Cache headers let clients skip downloads they already have.
- HTTP server: Cookies (example): Cookies carry state between requests in the cookie and set-cookie headers.
- HTTP server: CORS (example): Browsers block cross-origin requests unless the server opts in with CORS headers.
- HTTP server: Graceful shutdown (example): Killing a server mid-request drops connections and loses work.
- HTTP server: Health checks (example): Health endpoints let load balancers and orchestrators decide what to do with a process.
- HTTP Server: Hello world (example): An example of an HTTP server that serves a "Hello World" message.
- HTTP server: Hot reload (example): Restarting a server by hand after every edit gets old fast.
- HTTP server: Paginating results (example): APIs that return lists need pagination so a single response stays small.
- HTTP server: Rate limiting (example): A rate limiter protects a server from clients that send too many requests.
- HTTP server: Request timeouts (example): A handler that depends on a slow upstream can hold a connection open forever.
- HTTP server: Routing (example): An example of an HTTP server that handles requests with different responses based on the incoming URL.
- HTTP server: Scaling across CPU cores (example): A single process handles requests on one core.
- HTTP server: Server-sent events (example): Server-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 files (example): An example of an HTTP server that serves files.
- HTTP server: Sessions (example): A session keeps a user logged in across requests.
- HTTP server: Streaming (example): An example HTTP server that streams a response back to the client.
- HTTP server: TLS (example): serve speaks HTTPS when given a certificate and private key.
- HTTP server: Verifying webhook signatures (example): Webhook senders sign each delivery so receivers can prove the payload came from them and was not tampered with in transit.
- HTTP server: WebSockets (example): An example of an HTTP server that handles websocket requests.
- Outbound WebSockets (example): Opening a WebSocket connection for real-time, bi-directional communication with Ende is very simple.
- Piping streams (example): Ende implements web-standard streams which comes with many advantages.
- Proxy HTTP requests (example): A reverse proxy receives requests and forwards them to another server.
- Route fetch through an HTTP proxy (example): Ende 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 queries (example): There are some cases when running DNS queries is useful.
- Sign in with GitHub (OAuth) (example): The OAuth authorization code flow lets users sign in with an existing account.
- TCP connector: Ping (example): An example of connecting to a TCP server on localhost and writing a "ping" message to the server.
- TCP Echo Server (example): An 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: Ping (example): An 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: Ping (example): An example of connecting to a TCP server using TLS on localhost and writing a "ping" message to the server.
- TCP/TLS listener: Ping (example): An 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 WebSocketStream (example): WebSocketStream is a promise-based alternative to the event-based WebSocket API.
- UDP connector: Ping (example): An example of writing a 'ping' message to a UDP server on localhost.
- UDP listener: Ping (example): An 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) (example): Some protocols start as plaintext and negotiate encryption mid-connection instead of connecting over TLS from the start.
- WebSocket server: Broadcasting messages (example): Chat rooms, live dashboards, and multiplayer games all need one thing: deliver a message from one client to all the others.
- WebSocket server: Per-socket state (example): Most WebSocket servers need to know who each socket belongs to: a username, a room, a session.
File system
- Checking for directory existence (example): When creating directories it can be useful to first ensure that such a directory doesn’t already exist.
- Checking for file existence (example): When creating files it can be useful to first ensure that such a file doesn’t already exist.
- Convert between file URLs and paths (example): Modules are identified by URLs in Ende, while file system APIs take paths.
- Copy a file (example): Copying a file is a single call in Ende.
- Create and extract tar archives (example): gz format.
- Create hard links (example): A hard link is a second name for the same file.
- Creating & removing directories (example): Creating and removing directories is a common task.
- Creating & resolving symlinks (example): Creating and resolving symlink is a common task.
- Deleting files (example): Removing files and directories is a common task.
- File system events (tutorial): Tutorial on monitoring file system changes with Ende.
- Find files with glob patterns (example): Glob 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 file (example): Serving a file over HTTP needs a content type header.
- Lock files across processes (example): When two processes write the same file at the same time, the result is a mess.
- Moving/Renaming files (example): An example of how to move and rename files and directories in Ende.
- Path operations (example): Many applications need to manipulate file paths in one way or another.
- Read and change file metadata (example): Every file carries metadata besides its contents: size, timestamps, type and permissions.
- Reading files (example): Many applications need to read files from disk.
- Streaming file operations (example): Sometimes we need more granular control over file operations.
- Temporary files & directories (example): Temporary files and directories are used to store data that is not intended to be permanent.
- Truncate a file (example): Truncating sets a file to an exact length without rewriting its contents.
- Unix cat (example): In Unix, the `cat` command is a utility that reads files and writes them to standard output.
- Walking directories (example): When doing something like filesystem routing, it is useful to be able to walk down a directory to visit files.
- Watching the filesystem (example): When creating frameworks or CLI tools, it is often necessary to watch the filesystem for changes.
- Write a file incrementally (example): Writing a file all at once is fine until the data is large or arrives in pieces, like a download or a log.
- Writing files (example): Many applications need to write files to disk.
System
- Call C functions with FFI (example): The Foreign Function Interface lets Ende call functions in native shared libraries directly, with no glue code or build step.
- Collecting output from subprocesses (example): We don’t often write programs in isolation.
- Create a subprocess (tutorial): A guide to working with subprocesses in Ende.
- Detect a TTY and get terminal size (example): A program can check whether it is talking to a real terminal or to a pipe.
- Environment variables (example): Environment variables can be used to configure the behavior of a program, or pass data from one program to another.
- Find an executable on the PATH (example): Before spawning a tool like git or ffmpeg, it is useful to know whether it is installed and where.
- Get operating system information (example): Scripts 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 (tutorial): Tutorial on handling operating system signals in Ende.
- List network interfaces (example): networkInterfaces lists every network address of the machine.
- Listen for OS signals (example): addSignalListener` function.
- Pipe data into a subprocess (example): Many command line tools read their input from stdin.
- Process information (example): An example of how to access the current process ID and parent process ID.
- Read from stdin (example): Command line tools that work in pipelines read their input from stdin.
- Reading system metrics (example): This example demonstrates how to use Ende’s built-in methods to read system metrics such as memory information, load averages and memory usage.
- Run a subprocess with custom env and cwd (example): A subprocess normally inherits the environment variables and working directory of its parent.
- Set and read process exit codes (example): The 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 zone (example): Date, Intl, and Temporal all format times in the process time zone, which defaults to the operating system setting.
- Subprocesses: Spawning (example): For more complex usecases, we don’t simply want the output of some command.
- Write to stdout (example): 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
- Better debugging with the console API (tutorial): An in-depth guide to advanced console debugging in Ende.
- Build and send forms with FormData (example): FormData 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 API (example): Ende implements the Web Cache API from service workers.
- Cancel async work with AbortController (example): AbortController produces an AbortSignal that can cancel fetch requests, remove event listeners, and stop any code that checks the signal.
- Communicate between workers with BroadcastChannel (example): BroadcastChannel is a named bus.
- Create and dispatch custom events (example): EventTarget is the eventing system behind the DOM, and it works as a base class for your own types.
- Deep clone objects with structuredClone (example): structuredClone deep copies a value, so changes to the copy never leak back into the original.
- Distribute work across a worker pool (example): A single web worker moves heavy computation off the main thread, but a pool of workers uses every CPU core.
- Escape an HTML string (example): Interpolating user input into HTML without escaping it opens the door to cross-site scripting.
- Extract links and metadata from HTML (example): Scrapers, link checkers, and preview cards all start the same way: fetch a page and pull data out of its HTML.
- Fetch and stream data (tutorial): A tutorial on working with network requests in Ende.
- Format dates for any locale (example): DateTimeFormat turns a Date into text for any locale and time zone.
- Format numbers and currencies (example): NumberFormat formats numbers for any locale and style.
- Format relative time (example): RelativeTimeFormat produces phrases like 3 days ago or in 2 months for any locale.
- Logging with colors (example): Most modern terminals can display program logs in colors and with text decorations.
- Manipulating & parsing URLs (example): URL is the web standard interface to parse and manipulate URLs.
- Match URLs with URLPattern (example): URLPattern matches URLs against route-style patterns and extracts the dynamic parts.
- Measure performance with marks and measures (example): The performance API measures elapsed time with sub-millisecond precision.
- Parse and format dates (example): Everyday date work is parsing a value, formatting it for people, and doing arithmetic on it.
- Pluralize and format lists (example): Hand-rolled pluralization like adding an s breaks as soon as you leave English.
- Run a compute shader with WebGPU (example): WebGPU 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 fetch (example): timeout builds one that aborts after a given number of milliseconds.
- Set timeout and intervals (example): Timers are used to schedule functions to happen at a later time.
- Split text by words, sentences, and graphemes (example): Splitting text with split or slice breaks on punctuation, emoji, and languages that do not use spaces.
- Temporal API (example): An example of using the Temporal API to work with dates, times, and timestamps.
- Transform data with TransformStream (example): A TransformStream sits in the middle of a stream pipeline and rewrites chunks as they pass through.
- Web assembly (example): WebAssembly is a binary format for describing a program’s data and instructions.
- Web workers (example): Workers are the only way of running javascript off of the main thread.
Standard library
- Add a timeout to any promise (example): A promise has no built-in time limit, so a stalled request can hang a program forever.
- Convert string case (example): Identifiers, file names, CSS classes, and database columns all expect different casing conventions.
- Debounce a function (example): A debounced function waits until calls stop arriving before it runs.
- Escape text for regular expressions (example): Building a RegExp from user input is dangerous, because characters like parentheses and dots have special meaning in patterns.
- Exponential backoff (example): Exponential backoff is a technique used in computer systems to handle retries and avoid overwhelming services.
- Format bytes and durations for humans (example): Raw numbers like 1536 bytes or 97000 milliseconds are hard to read in logs and user interfaces.
- Generate seeded random numbers (example): random gives you no way to set a seed, so test runs and simulations that need reproducible randomness cannot use it.
- Memoize an expensive function (example): Memoization caches the result of a function call so repeated calls with the same arguments return instantly.
- Parse and compare semver versions (example): 0" alphabetically.
- Run async tasks with a concurrency limit (example): Firing hundreds of requests at once can overwhelm a server or hit rate limits.
- Structured logging (example): The @std/log package routes log records through configurable handlers with severity levels.
- User Data Processing with Ende Collections (example): Demonstrates using Ende’s @ende/collections library for processing user data.
Encoding
- Compress and decompress data (example): Compressing data before storing or sending it saves space and bandwidth.
- Convert a Blob (example): Blobs show up whenever you handle files or multipart form data, since an uploaded File is a Blob too.
- Convert a ReadableStream (example): Network responses, file handles, and subprocess output all hand you a ReadableStream.
- Convert a string to bytes and back (example): Hashing, file writes, and network protocols all want bytes, not strings.
- Convert a Uint8Array (example): Uint8Array is the workhorse binary type in Ende: file reads, network payloads, and hashes all produce or consume it.
- Convert an ArrayBuffer (example): An ArrayBuffer is a chunk of raw memory with no read or write interface of its own.
- Encode and decode CBOR (example): CBOR is a binary serialization format standardized as RFC 8949.
- Encode and decode MessagePack (example): MessagePack is a binary serialization format with the same data model as JSON.
- Extract front matter from markdown (example): Front matter is a metadata block at the top of a markdown file, fenced by --- lines and usually written in YAML.
- Hex and base64 encoding (example): Binary data often needs to travel as text, in URLs, JSON, or HTTP headers.
- Importing bytes (example): Binary files can be imported in JS and TS files using the `import` keyword.
- Importing JSON (example): JSON files can be imported in JS and TS files using the `import` keyword.
- Importing text (example): Text files can be imported in JS and TS files using the `import` keyword.
- Manipulating byte arrays (example): When working with lower-level data we often deal with byte arrays in the form of Uint8Arrays.
- Parse and generate XML (example): The @libs/xml package on JSR converts XML in both directions: XML text to plain JavaScript objects and back.
- Parse large CSV files as streams (example): Reading a whole CSV file into memory does not work once the file grows to gigabytes.
- Parsing and serializing CSV (example): CSV is a data serialization format that is designed to be portable for table-like applications.
- Parsing and serializing INI (example): INI is a plain text configuration format built from key value pairs that can be grouped into sections.
- Parsing and serializing JSON (example): JSON is a widely used data interchange format.
- Parsing and serializing TOML (example): TOML is a widely used configuration language designed to be feature-rich and intuitive to write.
- Parsing and serializing YAML (example): YAML is a widely used data serialization language designed to be easily human readable and writeable.
- Parsing JSONC (example): JSONC is JSON extended with comments and trailing commas, which makes it a friendlier format for configuration files that humans edit.
- Stream JSON Lines data (example): JSON Lines, also called NDJSON, stores one JSON value per line.
CLI
- Build a CLI with subcommands (example): Tools like git and ende itself take a subcommand first and flags after it.
- Command line arguments (example): Command line arguments are often used to pass configuration options to a program.
- Compile a script into an executable (example): The ende compile subcommand turns a script and all of its dependencies into a single self-contained binary.
- Control the terminal with ANSI escape codes (example): Terminals 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 (tutorial)
- Find and update outdated dependencies (example): Dependencies pinned months ago quietly fall behind.
- Getting the Ende version (example): How to examine the version of Ende being used.
- Input prompts (example): Prompts are used to ask the user for input or feedback on actions.
- Permission management (example): There are times where depending on the state of permissions granted to a process, we want to do different things.
- Show progress bars and spinners (example): Long-running command line tools feel broken when they print nothing.
- Write benchmarks with Ende.bench (example): Ende has a built-in benchmark runner.
Cryptography
- AES Encryption and Decryption (example): This example demonstrates AES encryption and decryption using Ende’s built-in SubtleCrypto API.
- Compare secrets in constant time (example): An 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 passwords (example): A password is not an encryption key: it is short, low entropy, and the wrong size for AES.
- Generate secure random values (example): Session tokens, password reset links, and API keys must be impossible to guess.
- Generating & validating UUIDs (example): UUIDs (universally unique identifier) can be used to uniquely identify some object or data.
- Hash large files with streams (example): The Web Crypto digest function takes a single buffer, so hashing a file with it means reading the whole file into memory first.
- Hashing (example): Hashing data is a common operation that is facilitated through Ende’s support for the Web Crypto API.
- Hashing and verifying passwords (example): Passwords must never be stored in plain text, and a plain digest like SHA-256 is too fast to resist brute force.
- HMAC Generation and Verification (example): This example demonstrates how to generate and verify an HMAC (Hash-based Message Authentication Code) using Ende’s built-in SubtleCrypto API with the SHA-256 hash function.
- RSASSA-PKCS1-v1_5 Signature and Verification (example): This example demonstrates RSA signature and verification using Ende’s built-in SubtleCrypto API.
- Shamir's Secret Sharing (example): This example demonstrates Shamir’s Secret Sharing, where a secret, split into shares, allows its reconstruction only when a sufficient number of shares are combined.
- Sign and verify data with ECDSA (example): A digital signature proves that a message was produced by the holder of a private key and was not modified in transit.
- ULID (example): One common need for distributed systems are identifiers.
Testing
- Basics of testing (tutorial): Learn key concepts like test setup and structure, assertions, async testing, mocking, test fixtures, and code coverage
- BDD testing (tutorial): Implementing Behavior-Driven Development with Ende’s Standard Library’s BDD module.
- Filtering and controlling test runs (example): The 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 (tutorial)
- Skipping and focusing tests (example): Sometimes 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 (tutorial)
- Spy functions (example): A function spy allows us to assert that a function was called with the correct arguments and a specific number of times.
- Testing web applications (tutorial): A comprehensive guide to testing web applications with Ende
- Writing tests (example): One of the most common tasks in developing software is writing tests for existing code.
Web frameworks and libraries
- Build a word finder app (tutorial): A tutorial on creating a word search application with Ende.
- Generate a QR code (example): A QR code encodes a short piece of text, usually a URL, as a scannable image.
- HTTP server file upload (example): An example HTTP server that provides sending and receiving of a file upload.
- Render markdown to HTML (example): The @ende/markdown module parses CommonMark and GitHub Flavored Markdown and renders it to HTML: tables, task lists, footnotes and GitHub’s alerts.
Databases
- Overview (tutorial): Connect Ende to SQLite and PostgreSQL with database drivers from JSR.
Scheduling
- Ende.cron (example): cron is a cron task scheduler built into the Ende runtime.
AI
- LLM Chat app (tutorial): Learn how to integrate Large Language Models (LLM) with Ende to create an interactive roleplay chat application with AI characters using OpenAI or Anthropic APIs.
Deploying Ende projects
OpenTelemetry
- Basic OpenTelemetry setup (tutorial): Set up basic OpenTelemetry instrumentation in an Ende application.
- Export telemetry to Grafana (tutorial): Complete guide to exporting telemetry data with OpenTelemetry and Grafana.
- Export telemetry to Honeycomb (tutorial): io.
- Export telemetry to Hyperdx (tutorial): Complete guide to exporting telemetry data with OpenTelemetry and HyperDX.
- Span propagation (tutorial): Implement end-to-end distributed tracing with automatic context propagation in Ende applications.