### Install via Homebrew Source: https://txikijs.org/docs/getting-started Install txiki.js on macOS and Linux using Homebrew. ```bash brew install saghul/tap/txikijs ``` -------------------------------- ### Install and run in CI Source: https://txikijs.org/docs/guides/mise Install the pinned tools from mise.toml and then run the app through mise exec in CI. ```bash mise install mise exec -- tjs run app.js ``` -------------------------------- ### Install via WinGet Source: https://txikijs.org/docs/getting-started Install txiki.js on Windows using the WinGet package manager. ```bash winget install Saghul.TxikiJS ``` -------------------------------- ### Install libffi with vcpkg on Windows Source: https://txikijs.org/docs/building Install the libffi dependency using vcpkg. ```powershell .\vcpkg install libffi ``` -------------------------------- ### Manifest: app.json example Source: https://txikijs.org/docs/guides/app-packages Example manifest with `version`, `build`, and `main` fields. `version` must be `0`, `build` is populated automatically, and `main` defaults to `src/main.js`. ```json { "version": 0, "build": {}, "main": "src/main.js" } ``` -------------------------------- ### wasi.start(instance) Source: https://txikijs.org/docs/api/tjs-wasi Starts the WebAssembly instance with the WASI interface. ```APIDOC ## wasi.start(instance) ### Description Starts the WebAssembly instance with the WASI interface. ### Method `start(instance: WebAssembly.Instance)` ### Parameters - **instance** (WebAssembly.Instance) - Required - The WebAssembly instance to start. ### Example ```js wasi.start(instance); ``` ``` -------------------------------- ### Install via Scoop Source: https://txikijs.org/docs/getting-started Install txiki.js on Windows using the Scoop package manager. ```bash scoop install txikijs ``` -------------------------------- ### Server startup output Source: https://txikijs.org/docs/guides/serve Example output printed by the server on startup, showing the address it is listening on. ```text Listening on http://localhost:8000/ ``` -------------------------------- ### serve(options) Source: https://txikijs.org/docs/api/global.tjs.Function.serve Starts an HTTP server with the provided options or fetch handler. Returns a Server instance. ```APIDOC ## serve(options) ### Description Starts an HTTP server with the provided options or fetch handler. Returns a Server instance. ### Method serve ### Endpoint serve(options) ### Parameters #### options - **options** (ServeOptions | FetchHandler) - Required - Server options or a fetch handler function. ### Request Example ```js const server = tjs.serve({ fetch(request) { return new Response('Hello World!'); }, port: 8080, }); ``` ### Response #### Success Response - **Server** - The server instance. #### Response Example ```js const server = tjs.serve((request) => new Response('Hello!')); ``` ### Notes - To enable HTTPS, provide TLS certificate and key as PEM strings in the `tls` option. - `close()` returns a promise that resolves once the server has fully shut down; prefer `await server.close()` (or `await using`) when you need to wait for the listening socket to be released. ``` -------------------------------- ### Start HTTP server with tjs.serve() Source: https://txikijs.org/docs/api/global.tjs.Function.serve Starts an HTTP server on port 8080 that responds with 'Hello World!' to every request. The fetch handler is defined in the options object. ```javascript const server = tjs.serve({ fetch(request) { return new Response('Hello World!'); }, port: 8080, }); ``` -------------------------------- ### start(instance) Source: https://txikijs.org/docs/api/tjs-wasi.Class.WASI Starts the WASI instance, running its `_start` export. Returns the exit code passed to `proc_exit()` (or `0` on a clean return). When `returnOnExit` is `false`, the process is terminated with that code and this function does not return. ```APIDOC ## Method: start(instance) ### Description Starts the WASI instance, running its `_start` export. Returns the exit code passed to `proc_exit()` (or `0` on a clean return). When `returnOnExit` is `false`, the process is terminated with that code and this function does not return. ### Parameters - **instance** (`Instance`) - Required - The WebAssembly instance to start. ### Returns `number` - The exit code. ``` -------------------------------- ### Instantiate and start a WASI module Source: https://txikijs.org/docs/api/tjs-wasi Creates a WASI instance with the 'wasi_snapshot_preview1' version, reads a WebAssembly module from 'module.wasm', instantiates it with the WASI import object, and starts the instance. This is the primary usage pattern for running WASI modules. ```javascript import { WASI } from 'tjs:wasi'; const wasi = new WASI({ version: 'wasi_snapshot_preview1' }); const { instance } = await WebAssembly.instantiate( await tjs.readFile('module.wasm'), wasi.getImportObject(), ); wasi.start(instance); ``` -------------------------------- ### Direct CMake example for optional features Source: https://txikijs.org/docs/building Configure and build with both BUILD_WITH_WASM=OFF and BUILD_WITH_SQLITE=OFF. The flags can be combined. ```bash cmake -B build-slim -DCMAKE_BUILD_TYPE=Release -DBUILD_WITH_WASM=OFF -DBUILD_WITH_SQLITE=OFF cmake --build build-slim ``` -------------------------------- ### Read a file and start an HTTP server Source: https://txikijs.org/docs/api/global Shows how to read a text file and decode it, and how to start an HTTP server using the tjs global. The snippet defines a fetch handler that returns a 'Hello!' response and binds the server to port 3000. ```javascript // Read a file const data = await tjs.readFile('hello.txt'); console.log(new TextDecoder().decode(data)); // Start an HTTP server const server = tjs.serve({ fetch: () => new Response('Hello!'), port: 3000, }); ``` -------------------------------- ### Verify mise installation Source: https://txikijs.org/docs/guides/mise Verify that mise is installed and available on your PATH before using it to manage txiki.js. ```bash mise --version ``` -------------------------------- ### Bootstrap vcpkg on Windows Source: https://txikijs.org/docs/building Clone vcpkg and run the bootstrap script to prepare it for installing dependencies. ```powershell git clone https://github.com/microsoft/vcpkg.git cd vcpkg .\bootstrap-vcpkg.bat ``` -------------------------------- ### Install cmake on macOS Source: https://txikijs.org/docs/building Install cmake using Homebrew on macOS. ```bash brew install cmake ``` -------------------------------- ### Quick start: scaffold, run, and compile a TPK app Source: https://txikijs.org/docs/guides/app-packages Commands to scaffold a new app with `tjs app init`, run it during development with `tjs run app/src/main.js`, and package it as a standalone executable with `tjs app compile myapp` followed by `./myapp`. ```bash # Scaffold a new app tjs app init # Run it directly during development tjs run app/src/main.js # Package as a standalone executable tjs app compile myapp ./myapp ``` -------------------------------- ### Install dependencies on Debian/Ubuntu Source: https://txikijs.org/docs/building Install build-essential, cmake, and libffi-dev on Debian/Ubuntu. Requires version >= 24.04. ```bash # On Debian / Ubuntu # version `>= 24.04` required sudo apt install build-essential cmake libffi-dev ``` -------------------------------- ### Direct CMake example for size-optimized builds Source: https://txikijs.org/docs/building Configure and build with MinSizeRel, strip, LTO, and GC sections. These flags shrink the binary without removing features. Note that MinSizeRel optimizes for size over speed. ```bash cmake -B build-min -DCMAKE_BUILD_TYPE=MinSizeRel \ -DBUILD_WITH_STRIP=ON -DBUILD_WITH_LTO=ON -DBUILD_WITH_GC_SECTIONS=ON cmake --build build-min ``` -------------------------------- ### dlopen Source: https://txikijs.org/docs/api/tjs-ffi Example of using the dlopen function to load a native library and call a function. ```APIDOC ## [FUNCTION] dlopen ### Description Loads a shared library and returns its symbols. The function takes a library name and a set of symbol definitions, and returns an object containing the loaded symbols. ### Signature `dlopen(libraryName: string, symbols: Record): DlopenResult` ### Parameters - **libraryName** (string) - Required - The name of the shared library to load. - **symbols** (Record) - Required - An object mapping symbol names to their type definitions (e.g., `{ returns: 'i32' }`). ### Return Value - **DlopenResult** - An object containing the loaded symbols, accessible via the `symbols` property. ### Example ```js import { dlopen } from 'tjs:ffi'; const { symbols } = dlopen('c', { getpid: { returns: 'i32' }, }); console.log(`PID: ${symbols.getpid()}`); ``` ``` -------------------------------- ### Add txiki.js to a project with mise use Source: https://txikijs.org/docs/guides/mise Install the latest txiki.js release from GitHub Releases and write a mise.toml with the version and executable configuration. ```bash mise use "github:saghul/txiki.js[exe=tjs]" ``` -------------------------------- ### Start interactive REPL Source: https://txikijs.org/docs/getting-started Launch the interactive REPL by running the tjs command without arguments. ```bash tjs ``` -------------------------------- ### Serve over HTTPS with tjs serve Source: https://txikijs.org/docs/guides/serve Starts the tjs server with TLS using the generated certificate and key. The startup log reflects the https:// scheme. ```bash tjs serve --tls-cert cert.pem --tls-key key.pem app.js ``` -------------------------------- ### Start the tjs REPL Source: https://txikijs.org/docs/cli Starts the interactive REPL when run on a TTY. Provides syntax-highlighted output and persistent command history. ```bash tjs ``` -------------------------------- ### Run mise tasks Source: https://txikijs.org/docs/guides/mise Run the defined tasks. The first runs the start task, the second runs the test task, and the third opens an interactive TUI to select a task. ```bash mise run start # or: mise start mise run test # or: mise test mise run # interactive TUI ``` -------------------------------- ### Install dependencies on Amazon Linux 2023 Source: https://txikijs.org/docs/building Install git, gcc14, gcc14-c++, cmake, libffi-devel, and libatomic on Amazon Linux 2023. Also creates symlinks for cc and c++. ```bash # Amazon Linux, al.2023 dnf install -y git gcc14 gcc14-c++ cmake libffi-devel libatomic ln -s /usr/bin/gcc14-gcc /usr/bin/cc ln -s /usr/bin/gcc14-c++ /usr/bin/c++ ``` -------------------------------- ### Enable HTTPS with TLS certificates Source: https://txikijs.org/docs/api/global.tjs.Function.serve Starts an HTTPS server on port 8443. Requires PEM-encoded certificate and key files, read and decoded as strings, and passed in the tls option. ```javascript const cert = new TextDecoder().decode(await tjs.readFile('cert.pem')); const key = new TextDecoder().decode(await tjs.readFile('key.pem')); const server = tjs.serve({ fetch(request) { return new Response('Hello HTTPS!'); }, port: 8443, tls: { cert, key }, }); ``` -------------------------------- ### getopt() Source: https://txikijs.org/docs/api/tjs-posix-socket.Class.PosixSocket Gets a socket option. By default 128 bytes are reserved for the option, provide size argument for larger buffer or to save memory. ```APIDOC ## getopt() ### Description Gets a socket option. By default 128 bytes are reserved for the option, provide size argument for larger buffer or to save memory. ### Method getopt ### Signature `getopt(level: number, name: number, size?: number): Uint8Array` ### Parameters - **level** (`number`) - Required - The protocol level. - **name** (`number`) - Required - The option name. - **size** (`number`) - Optional - The buffer size for the option. ### Returns `Uint8Array` ``` -------------------------------- ### Create and run a transaction with prepared statement Source: https://txikijs.org/docs/api/tjs-sqlite.Class.Database Shows how to create a prepared statement and wrap it in a transaction function. The transaction function accepts an array of data and runs the prepared statement for each item. When the returned function is invoked, it starts a new transaction, commits on return, and rolls back on exception. ```javascript const ins = db.prepare('INSERT INTO test (txt, int) VALUES(?, ?)'); const insMany = db.transaction(datas => { for (const data of datas) { ins.run(data); } }); insMany([ [ '1234', 1234 ], [ '4321', 4321 ], ]); ``` -------------------------------- ### Import and use inspect and format from tjs:utils Source: https://txikijs.org/docs/api/tjs-utils Shows how to import the inspect and format functions from the tjs:utils module. The example logs an object with colors enabled and formats a string with placeholders. ```javascript import { inspect, format } from 'tjs:utils'; console.log(inspect({ a: 1, b: [2, 3] }, { colors: true })); console.log(format('Hello %s, you are %d', 'Alice', 30)); ``` -------------------------------- ### mise.toml for older txiki.js with ubi backend Source: https://txikijs.org/docs/guides/mise Example mise.toml for older txiki.js versions (<26.5.0) using the deprecated ubi backend. Note that ubi is deprecated and will be removed in mise 2027.1.0. ```toml [tools] "ubi:saghul/txiki.js" = { version = "26.4.0", exe = "tjs" } ``` -------------------------------- ### Define project tasks in mise.toml Source: https://txikijs.org/docs/guides/mise Define project tasks in mise.toml that use the pinned txiki.js runtime. The start task runs the main script, and the test task runs the test suite. ```toml [tools] "github:saghul/txiki.js" = { version = "26.6.0", exe = "tjs" } [tasks.start] run = "tjs run src/main.js" [tasks.test] run = "tjs test tests/" description = "Run the test suite" ``` -------------------------------- ### Install @txikijs/types Source: https://txikijs.org/docs/typescript Install the @txikijs/types package as a dev dependency to get TypeScript type definitions for txiki.js APIs, enabling autocompletion and type checking. ```bash npm install @txikijs/types --save-dev ``` -------------------------------- ### WebSocketStream with Custom Headers Source: https://txikijs.org/docs/features/web-platform-apis Shows how to pass custom HTTP headers to a WebSocketStream connection using the `headers` option. The example also demonstrates accessing the `opened` promise to get the readable and writable streams. ```javascript const wss = new WebSocketStream('wss://example.com/ws', { protocols: ['chat'], headers: { 'Authorization': 'Bearer my-token', }, }); const { readable, writable } = await wss.opened; ``` -------------------------------- ### Unix domain socket server and client with PipeServerSocket and PipeSocket Source: https://txikijs.org/docs/guides/networking Shows how to create a Unix domain socket server and client using PipeServerSocket and PipeSocket. The server listens on a filesystem path and echoes each connection; the client connects and writes a ping message. Both use the opened promise to get streams. ```javascript const server = new PipeServerSocket('/tmp/fooPipe'); const { readable, localAddress } = await server.opened; console.log(`Listening on ${localAddress}`); const reader = readable.getReader(); while (true) { const { value: conn, done } = await reader.read(); if (done) { break; } const { readable: r, writable: w } = await conn.opened; r.pipeTo(w); // echo } ``` ```javascript const client = new PipeSocket('/tmp/fooPipe'); const { writable } = await client.opened; const writer = writable.getWriter(); await writer.write(new TextEncoder().encode('ping\n')); ``` -------------------------------- ### Declare symbols from C prototypes with dlopenCProto Source: https://txikijs.org/docs/guides/ffi Paste C declarations to bind functions and get types. The example defines a struct point and a function point_sum, then calls it with a pointer to a struct. The types map contains StructType instances, which do not support string, enum, or counted-array shapes unless defined with defineStruct. ```javascript import { dlopenCProto, Pointer, suffix } from 'tjs:ffi'; const { symbols, types, close } = dlopenCProto(`./libmystuff.${suffix}`, ` struct point { int x; int y; }; int point_sum(struct point *p); `); const Point = types.get('struct point'); console.log(symbols.point_sum(Pointer.createRef(Point, { x: 3, y: 4 }))); // 7 close(); ``` -------------------------------- ### Pass esbuild options to tjs bundle Source: https://txikijs.org/docs/guides/code-bundling Any esbuild CLI option can be passed to `tjs bundle`. This example uses `--minify`, `--define:DEBUG=true`, and `--drop:debugger`. ```bash tjs bundle --minify --define:DEBUG=true --drop:debugger my-app/index.ts ``` -------------------------------- ### Load a library and call functions with dlopen Source: https://txikijs.org/docs/guides/ffi Use dlopen to load a library and declare symbols. The example loads the C library, calls getpid and abs, then closes the handle. The symbol map declares functions with args and returns types. ```javascript import { dlopen } from 'tjs:ffi'; const { symbols, close } = dlopen('c', { getpid: { returns: 'i32' }, abs: { args: ['i32'], returns: 'i32' }, }); console.log('pid:', symbols.getpid()); console.log('abs(-5):', symbols.abs(-5)); close(); // release the library handle when done ``` -------------------------------- ### Create and bind a POSIX socket Source: https://txikijs.org/docs/api/tjs-posix-socket Imports the PosixSocket class from 'tjs:posix-socket', creates a TCP socket, binds it to 127.0.0.1:8080, and starts listening with a backlog of 128. Requires the module to be available (not on Windows). ```javascript import { PosixSocket } from 'tjs:posix-socket'; const { AF_INET, SOCK_STREAM, IPPROTO_TCP } = PosixSocket.defines; const sock = new PosixSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP); const addr = PosixSocket.createSockaddrIn('127.0.0.1', 8080); sock.bind(addr); sock.listen(128); ``` -------------------------------- ### Build and run the compiled app Source: https://txikijs.org/docs/guides/app-packages Compiles the multi-file app into an executable named hello, then runs it. The output is Hello, world!. ```bash tjs app compile hello ./hello # Hello, world! ``` -------------------------------- ### Load shared library with dlopen and bind symbols Source: https://txikijs.org/docs/api/tjs-ffi.Function.dlopen Loads a shared library and binds its functions as callable symbols. The example uses a macOS library path and defines two symbols: 'add' with two i32 arguments and an i32 return, and 'version' with no arguments and a string return. After calling the bound functions, the library is closed with close(). ```javascript import { dlopen } from 'tjs:ffi'; const { symbols, close } = dlopen('./libfoo.dylib', { add: { args: ['i32', 'i32'], returns: 'i32' }, version: { args: [], returns: 'string' }, }); console.log(symbols.add(1, 2)); console.log(symbols.version()); close(); ``` -------------------------------- ### Initialize a template app with tjs app init Source: https://txikijs.org/docs/guides/app-packages Creates a template app in the current directory. Generates app/app.json with an empty build section and app/src/main.js as a hello-world entry point. Errors if the app/ directory already exists. ```bash tjs app init ``` -------------------------------- ### Build and run txiki.js on Unix systems Source: https://txikijs.org/docs/building Clone the repository recursively, compile with make, and run the REPL with ./build/tjs. ```bash # Get the code git clone --recursive https://github.com/saghul/txiki.js --shallow-submodules && cd txiki.js # Compile it! make # Run the REPL ./build/tjs ``` -------------------------------- ### Edit app/src/main.js Source: https://txikijs.org/docs/guides/app-packages Entry point for the multi-file app. Imports and calls the greet function from the local lib module. ```javascript import { greet } from './lib/greet.js'; greet('world'); ``` -------------------------------- ### View CLI help Source: https://txikijs.org/docs/getting-started Display all available subcommands and options for the tjs CLI. ```bash tjs --help ``` -------------------------------- ### FileHandle.stat() Source: https://txikijs.org/docs/api/global.tjs.Interface.FileHandle Gets the file status information. See stat(2). ```APIDOC ## stat() ### Description Get the file status information. See stat(2). ### Method stat ### Returns `Promise` ``` -------------------------------- ### WASIOptions Interface Source: https://txikijs.org/docs/api/tjs-wasi.Interface.WASIOptions Defines the configuration object used when starting a WASI application. ```APIDOC ## WASIOptions ### Properties #### args? - Type: `string[]` - Optional - Command line arguments. #### env? - Type: `Record` - Optional - Environment variables as key-value pairs. #### preopens? - Type: `Record` - Optional - Pre-opened directories mapping guest paths to host paths. #### returnOnExit? - Type: `boolean` - Optional - Default: `true` - By default, when the WASI application calls `proc_exit()`, WASI.start returns the exit code rather than terminating the process. Set to `false` to make the process exit with that code instead. #### stderr? - Type: `number` - Optional - Default: `2` - The file descriptor used as standard error in the WASI application. On Windows this must be a regular file or standard-stream fd; sockets and pipes are not supported. #### stdin? - Type: `number` - Optional - Default: `0` - The file descriptor used as standard input in the WASI application. On Windows this must be a regular file or standard-stream fd; sockets and pipes are not supported. #### stdout? - Type: `number` - Optional - Default: `1` - The file descriptor used as standard output in the WASI application. On Windows this must be a regular file or standard-stream fd; sockets and pipes are not supported. #### version - Type: `WASIVersion` - Required - The WASI version to use. ``` -------------------------------- ### Create app/src/lib/greet.js Source: https://txikijs.org/docs/guides/app-packages Exports the greet function used by main.js. Logs a greeting to the console. ```javascript export function greet(name) { console.log(`Hello, ${name}!`); } ``` -------------------------------- ### tjs.serve(options) - Full Configuration Source: https://txikijs.org/docs/guides/serve Creates an HTTP server with full configuration options, including port, TLS certificates, and a fetch handler. Returns a Server object that can be closed or used with async iteration. ```APIDOC ## tjs.serve(options) ### Description Creates an HTTP server with full configuration options, including custom bind address, TLS configuration, and a request handler. This is the programmatic equivalent of the `tjs serve` CLI. ### Signature `tjs.serve(options: ServeOptions)` ### Parameters #### options (ServeOptions) - **port** (number) - Required - The port to listen on. - **tls** (TlsOptions) - Optional - TLS configuration with `cert` and `key` fields (in-memory PEM strings), plus optional `ca`, `passphrase`, and `requestCert`. - **fetch** (function) - Required - The request handler, receiving a `Request` object and returning a `Response`. - **http3** (boolean) - Optional - Set to `true` to serve HTTP/3 over QUIC on the same port. ### Request Example ```js const cert = new TextDecoder().decode(await tjs.readFile('cert.pem')); const key = new TextDecoder().decode(await tjs.readFile('key.pem')); const server = tjs.serve({ port: 8443, tls: { cert, key }, fetch(request) { return new Response('Hello HTTPS!\n'); }, }); console.log(`Listening on https://localhost:${server.port}/`); ``` ### Response #### Return Value - **Server** - The server object, exposing `port` and `await close()` methods. Also async-disposable, so `await using` works. ``` -------------------------------- ### new Database(dbName?, options?) Source: https://txikijs.org/docs/api/tjs-sqlite.Class.Database Constructor for the Database class. Opens a SQLite database with optional name and options. ```APIDOC ## Constructor ### new Database(dbName?, options?) Opens a SQLite database. #### Parameters - **dbName** (`string`, optional) - The path of the database. Defaults to `:memory:`, which opens an in-memory database. - **options** (`IDatabaseOptions`, optional) - Options when opening the database. #### Returns `Database` ``` -------------------------------- ### makeDir(path, options?) Source: https://txikijs.org/docs/api/global.tjs.Function.makeDir Documentation for the makeDir function, which creates a directory at a specified path. ```APIDOC ## makeDir(path, options?) ### Description Creates a directory at the given path. ### Signature `makeDir(path: string, options?: MakeDirOptions): Promise` ### Parameters - **path** (`string`) - Required - The path of the directory to be created. - **options** (`MakeDirOptions`) - Optional - Options for making the directory. ### Returns `Promise` - A promise that resolves when the directory is created. ``` -------------------------------- ### spawn(args, options?) Source: https://txikijs.org/docs/api/global.tjs.Function.spawn Spawns a child process with the given command line arguments and optional process options. ```APIDOC ## spawn(args, options?) ### Description Spawns a child process with the given command line arguments and optional process options. ### Signature `spawn(args: string | string[], options?: ProcessOptions): Process` ### Parameters - **args** (`string` | `string[]`) - Required - Command line arguments for the new process. - **options** (`ProcessOptions`) - Optional - Extra options. ### Returns - `Process` - The spawned process object. ``` -------------------------------- ### stat(path) Source: https://txikijs.org/docs/api/global.tjs.Function.stat Gets file status information for the specified path. Returns a Promise that resolves to a StatResult object. ```APIDOC ## stat(path) ### Description Gets file status information for the specified path. Returns a Promise that resolves to a StatResult object. ### Parameters - **path** (`string`) - Required - Path to the file. ### Returns `Promise` - A promise that resolves to the file status information. ``` -------------------------------- ### Import standard library modules Source: https://txikijs.org/docs/features/standard-library Shows how to import modules from the txiki.js standard library using the `tjs:` scheme. Includes imports for assert, path, and sqlite, and a simple assertion. ```javascript import assert from 'tjs:assert'; import { parse } from 'tjs:path'; import { Database } from 'tjs:sqlite'; assert.eq(1 + 1, 2); ``` -------------------------------- ### Terminal output for ubi backend Source: https://txikijs.org/docs/guides/mise Terminal output when using the ubi backend, showing the deprecation warning and the installation path. ```text mise WARN deprecated [ubi]: The ubi backend is deprecated. Use the github backend instead (e.g., github:owner/repo). This will be removed in mise 2027.1.0. mise Installed executable into /Users/you/.local/share/mise/installs/ubi-saghul-txiki-js/26.4.0/tjs ubi:saghul/txiki.js@26.4.0 checksum generate macos-arm64-tjs-tjs ``` -------------------------------- ### open(path, flags, mode?) Source: https://txikijs.org/docs/api/global.tjs.Function.open Opens a file at the specified path with the given flags and optional mode, returning a Promise that resolves to a FileHandle. ```APIDOC ## Function: open() ### Description Opens the file at the given path. Opening flags: 'r' for reading, 'w' for writing (truncating), 'x' for exclusive creation, 'a' for appending, and '+' for updating (reading and writing). Returns a Promise resolving to a FileHandle. ### Signature ```typescript open(path: string, flags: string, mode?: number): Promise ``` ### Parameters - **path** (`string`) - Required - The path to the file to be opened. - **flags** (`string`) - Required - Flags with which to open the file. Supported flags: 'r', 'w', 'x', 'a', '+'. - **mode?** (`number`) - Optional - File mode bits applied if the file is created. Defaults to `0o666`. ### Returns `Promise` - A Promise that resolves to a FileHandle for the opened file. ### Example ```typescript const f = await tjs.open('file.txt', 'r'); ``` ``` -------------------------------- ### Read a whole binary file with tjs.readFile Source: https://txikijs.org/docs/guides/filesystem Reads a binary file into a Uint8Array without decoding. The example logs the number of bytes read. ```javascript const png = await tjs.readFile('logo.png'); console.log(`read ${png.byteLength} bytes`); ``` -------------------------------- ### default(argv, options?) Source: https://txikijs.org/docs/api/tjs-getopts.Function.default Parses command-line arguments with optional configuration and returns the parsed options. ```APIDOC ## Function: default() ### Description Parses command-line arguments with optional configuration and returns the parsed options. ### Signature `default(argv: string[], options?: Options): ParsedOptions` ### Parameters - **argv** (`string[]`) - Required - Arguments to parse. - **options** (`Options`) - Optional - Parsing options (configuration). ### Returns - **ParsedOptions** - The parsed arguments. ``` -------------------------------- ### Recursively remove a directory tree with tjs.remove Source: https://txikijs.org/docs/guides/filesystem Deletes a directory tree recursively, similar to 'rm -rf'. The example removes the directory created earlier. ```javascript await tjs.remove(dir); ``` -------------------------------- ### Query filesystem stats with tjs.statFs() Source: https://txikijs.org/docs/guides/filesystem tjs.statFs() resolves to a StatFsResult with fields like bavail and bsize. This example calculates free bytes and prints them in GB. ```javascript const fs = await tjs.statFs('/'); const freeBytes = fs.bavail * fs.bsize; console.log(`${(freeBytes / 1e9).toFixed(1)} GB free`); ``` -------------------------------- ### Configure and build with CMake on Windows Source: https://txikijs.org/docs/building Configure the build with the vcpkg toolchain file and build the Release configuration. The executable will be at build\Release\tjs.exe. ```powershell cmake -B build -DCMAKE_TOOLCHAIN_FILE=path/to/vcpkg/scripts/buildsystems/vcpkg.cmake cmake --build build --config Release ``` -------------------------------- ### Regenerate JS runtime C code Source: https://txikijs.org/docs/building Install JS dependencies and bundle the code into C source files. Required when modifying JS files in the runtime. ```bash # First install the JS dependencies npm install # Now bundle the code and compile it into C source files make js ``` -------------------------------- ### new PipeServerSocket(path, options?) Source: https://txikijs.org/docs/api/global.Class.PipeServerSocket Creates a new PipeServerSocket instance with the given path and optional options. ```APIDOC ## Constructor: new PipeServerSocket(path, options?) ### Description Creates a new PipeServerSocket instance. ### Parameters - **path** (`string`) - Required - The path for the pipe server socket. - **options?** (`PipeServerSocketOptions`) - Optional - Configuration options for the socket. ### Returns `PipeServerSocket` - The newly created instance. ``` -------------------------------- ### Write to a FileHandle with an offset Source: https://txikijs.org/docs/guides/filesystem Opens a file for reading and writing ('r+') and writes 5 bytes starting at byte 10 using the offset argument for random access. ```javascript const f = await tjs.open('data.bin', 'r+'); await f.write(new Uint8Array([0, 1, 2, 3, 4]), 10); await f.close(); ``` -------------------------------- ### Create a hash and read the digest Source: https://txikijs.org/docs/guides/hashing Demonstrates creating a SHA-256 hash, feeding it encoded bytes, and outputting the resulting hex digest. ```javascript import { createHash } from 'tjs:hashing'; const bytes = new TextEncoder().encode('hello world'); const digest = createHash('sha256').update(bytes).digest(); console.log(digest); // b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 ``` -------------------------------- ### Web Crypto digest example Source: https://txikijs.org/docs/guides/hashing Uses crypto.subtle.digest() to hash data asynchronously. Encodes the input with TextEncoder, awaits the digest, and converts the resulting ArrayBuffer to a hex string. ```javascript const data = new TextEncoder().encode('hello world'); const buf = await crypto.subtle.digest('SHA-256', data); const hex = [...new Uint8Array(buf)] .map(b => b.toString(16).padStart(2, '0')) .join(''); console.log(hex); ``` -------------------------------- ### App structure: app/ directory layout Source: https://txikijs.org/docs/guides/app-packages Shows the required directory layout for a TPK app, with `app.json` manifest and `src/main.js` entry point. ```text app/ app.json # manifest src/ main.js # entry point ... # other source files ``` -------------------------------- ### new UDPSocket(options) Source: https://txikijs.org/docs/api/global.Class.UDPSocket Creates a new UDPSocket instance with the provided options. ```APIDOC ## new UDPSocket(options) ### Description Creates a new UDPSocket instance. ### Constructor `new UDPSocket(options)` ### Parameters - **options** (`UDPSocketOptions`) - Required - The options for the UDP socket. ### Returns `UDPSocket` - A new UDPSocket instance. ``` -------------------------------- ### Chain update() calls for SHA-512 digest Source: https://txikijs.org/docs/guides/hashing Chaining update() calls adds each part to the running hash. This example hashes two string parts and prints the final digest. ```javascript import { createHash } from 'tjs:hashing'; const enc = new TextEncoder(); const digest = createHash('sha512') .update(enc.encode('part one ')) .update(enc.encode('part two')) .digest(); console.log(digest); ``` -------------------------------- ### MakeDirOptions Source: https://txikijs.org/docs/api/global.tjs.Interface.MakeDirOptions Options for creating a directory. Includes optional mode and recursive properties. ```APIDOC ## MakeDirOptions ### Description Options for creating a directory. Includes optional mode and recursive properties. ### Properties #### mode? - **type**: `number` - **optional**: true - **description**: The file mode for the new directory. Defaults to `0o777`. #### recursive? - **type**: `boolean` - **optional**: true - **description**: Whether the directories will be created recursively or not. Default to `false`. ``` -------------------------------- ### all(...args) Source: https://txikijs.org/docs/api/tjs-sqlite.Interface.IStatement Runs the SQL statement and returns an array of objects with column names and values. ```APIDOC ## all(...args) ### Description Runs the SQL statement, returning an array of objects with the name of the columns and matching values. ### Method all ### Parameters - **args** (`...any[]`) - The bound parameters for the statement. ### Returns `any[]` - An array of objects representing the result rows. ``` -------------------------------- ### Generate and validate a v7 UUID with tjs:uuid Source: https://txikijs.org/docs/api/tjs-uuid Generates a v7 UUID and validates it. The example logs the generated UUID and the result of the validate function, which returns true for a valid UUID. ```javascript import { v7, validate } from 'tjs:uuid'; const id = v7(); console.log(id); // e.g. '01932c08-e774-7484-a548-1ff098b05a47' console.log(validate(id)); // true ``` -------------------------------- ### loadExtension(file, entrypoint?) Source: https://txikijs.org/docs/api/tjs-sqlite.Class.Database Loads an extension from a shared library file. ```APIDOC ## Method: loadExtension ### loadExtension(file, entrypoint?): undefined Load an extension from file. #### Parameters - **file** (`string`) - location of the shared library - **entrypoint** (`string`, optional) - entrypoint, if left empty a guess is made by sqlite #### Returns `undefined` ``` -------------------------------- ### Zero-copy view with toUint8Array Source: https://txikijs.org/docs/guides/ffi Use `toUint8Array` to get a zero-copy view over native memory. The returned typed array aliases the native buffer, so writes go directly to native memory. ```javascript const p = symbols.get_pixels(); // NativePointer to width*height*4 bytes const pixels = p.toUint8Array(w * h * 4); // a view, not a copy pixels[0] = 255; // writes straight to the native buffer ``` -------------------------------- ### Create a TLS server with TLSServerSocket Source: https://txikijs.org/docs/guides/networking Creates a TLS server that requires a PEM certificate and key, listens on a local port, and echoes accepted client connections. The `opened` promise provides the local port. ```javascript const cert = new TextDecoder().decode(await tjs.readFile('cert.pem')); const key = new TextDecoder().decode(await tjs.readFile('key.pem')); const server = new TLSServerSocket('127.0.0.1', { localPort: 8443, cert, key, alpn: ['http/1.1'], }); const { readable, localPort } = await server.opened; console.log(`TLS listening on ${localPort}`); const reader = readable.getReader(); while (true) { const { value: conn, done } = await reader.read(); if (done) { break; } const { readable: r, writable: w } = await conn.opened; r.pipeTo(w); // echo } ``` -------------------------------- ### Compile app to executable with tjs app compile Source: https://txikijs.org/docs/guides/app-packages Compiles the app into a standalone executable. The resulting binary is fully self-contained, including the txiki.js runtime and the packaged app, so no installation is needed to run it. ```bash tjs app compile # writes ./app (or app.exe on Windows) ``` ```bash tjs app compile myapp # writes ./myapp ``` -------------------------------- ### accept() Source: https://txikijs.org/docs/api/tjs-posix-socket.Class.PosixSocket Accepts an incoming connection on a listening socket. ```APIDOC ## accept() ### Description Accepts an incoming connection on a listening socket. ### Method accept ### Signature `accept(): PosixSocket` ### Returns `PosixSocket` ``` -------------------------------- ### Handle errno with errno() and strerror() Source: https://txikijs.org/docs/guides/ffi Read errno after a libc-style function fails. The example calls chdir with a non-existent directory and prints the error message. The output is "No such file or directory". ```javascript import { dlopen, errno, strerror } from 'tjs:ffi'; const { symbols, close } = dlopen('c', { chdir: { args: ['string'], returns: 'int' }, }); if (symbols.chdir('/no/such/directory') < 0) { console.log('failed:', strerror(errno())); // "No such file or directory" } close(); ``` -------------------------------- ### listen() Source: https://txikijs.org/docs/api/tjs-posix-socket.Class.PosixSocket Listens for incoming connections on the socket. ```APIDOC ## listen() ### Description Listens for incoming connections on the socket. ### Method listen ### Signature `listen(backlog: number): void` ### Parameters - **backlog** (`number`) - Required - The maximum length of the queue of pending connections. ### Returns `void` ``` -------------------------------- ### Parse command line options with tjs:getopts Source: https://txikijs.org/docs/api/tjs-getopts Imports getopts from 'tjs:getopts' and parses tjs.args.slice(1) with aliases for help and version, and boolean options. Checks if the help option is set and prints usage. ```javascript import getopts from 'tjs:getopts'; const opts = getopts(tjs.args.slice(1), { alias: { h: 'help', v: 'version' }, boolean: ['help', 'version'], }); if (opts.help) { console.log('Usage: myapp [options]'); } ``` -------------------------------- ### Write to child stdin with WritableStream Source: https://txikijs.org/docs/guides/child-processes Set stdin to 'pipe' to get a WritableStream. Use getWriter() to write encoded data and close the writer to signal end-of-input. Read responses from stdout with getReader(). ```javascript const encoder = new TextEncoder(); const decoder = new TextDecoder(); const proc = tjs.spawn('cat', { stdin: 'pipe', stdout: 'pipe' }); const writer = proc.stdin.getWriter(); const reader = proc.stdout.getReader(); await writer.write(encoder.encode('hello!')); let chunk = await reader.read(); console.log(decoder.decode(chunk.value)); // "hello!" await writer.write(encoder.encode('hello again!')); chunk = await reader.read(); console.log(decoder.decode(chunk.value)); // "hello again!" writer.close(); const status = await proc.wait(); console.log(status); ``` -------------------------------- ### List available txiki.js versions Source: https://txikijs.org/docs/guides/mise List all available txiki.js versions from GitHub Releases so you can choose an exact version to pin. ```bash mise ls-remote "github:saghul/txiki.js" ``` -------------------------------- ### Keeping memory alive for zero-copy views Source: https://txikijs.org/docs/guides/ffi When the native memory is owned by a JavaScript object, keep a reference to that object alive while any view over its memory is in use. This example shows that writing through the view modifies the original `Uint8Array`. ```javascript import { bufferToPointer } from 'tjs:ffi'; const src = new Uint8Array([1, 2, 3, 4]); const view = bufferToPointer(src).toUint8Array(src.length); view[0] = 42; console.log(src[0]); // 42 — same memory; keep `src` reachable while `view` lives ``` -------------------------------- ### prepare(sql) Source: https://txikijs.org/docs/api/tjs-sqlite.Class.Database Creates a prepared statement for running SQL queries. ```APIDOC ## Method: prepare ### prepare(sql): IStatement Create a prepared statement, to run SQL queries. #### Parameters - **sql** (`string`) - The SQL query that will run. #### Returns `IStatement` ``` -------------------------------- ### Resolve DNS with tjs.lookup() Source: https://txikijs.org/docs/guides/networking Demonstrates tjs.lookup() for DNS resolution using getaddrinfo(3). By default it returns the first match as a single Addr object with { family, ip }; pass { all: true } to get an array of all results. ```javascript const addr = await tjs.lookup('example.com'); console.log(addr.ip, addr.family); const all = await tjs.lookup('example.com', { all: true }); for (const a of all) { console.log(a.ip); } ``` -------------------------------- ### Using tjs:path join, dirname, basename, extname Source: https://txikijs.org/docs/api/tjs-path Import the tjs:path module and use path.join to construct a path, then extract its directory, basename, and extension with path.dirname, path.basename, and path.extname. The expected outputs are shown in the comments. ```javascript import path from 'tjs:path'; const full = path.join('/home', 'user', 'docs', 'file.txt'); console.log(path.dirname(full)); // '/home/user/docs' console.log(path.basename(full)); // 'file.txt' console.log(path.extname(full)); // '.txt' ``` -------------------------------- ### List supported hashing algorithms with SUPPORTED_TYPES Source: https://txikijs.org/docs/guides/hashing Imports SUPPORTED_TYPES from 'tjs:hashing' and logs the array of supported algorithm names. The output shows the full list including MD5, SHA-1, SHA-2, and SHA-3 variants. ```javascript import { SUPPORTED_TYPES } from 'tjs:hashing'; console.log(SUPPORTED_TYPES); // [ // 'md5', 'sha1', 'sha224', 'sha256', // 'sha384', 'sha512', 'sha512_224', 'sha512_256', // 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512' // ] ``` -------------------------------- ### setImportMap() example Source: https://txikijs.org/docs/api/global.tjs.Function.setImportMap Calls setImportMap() with an import map that remaps bare specifiers and prefixes to local files, then dynamically imports 'lodash'. Must be called before the affected import runs; only one import map is active at a time. ```javascript tjs.setImportMap({ imports: { 'lodash': './vendor/lodash/index.js', 'lodash/': './vendor/lodash/', 'blocked': null, }, scopes: { './legacy/': { 'pkg': './vendor/pkg-v1/index.js', }, }, }, import.meta.dirname); const _ = await import('lodash'); ```