writeFile

A utility function for creating or updating files in a Val Town val via the Val Town SDK. Handles the create-or-update pattern automatically — if a file already exists (409 conflict), it falls back to updating it.

Usage

import { writeFile } from "https://esm.town/v/nbbaier/writeFile/index.ts"; const result = await writeFile({ path: "hello.txt", content: "Hello, world!", type: "file", callerUrl: import.meta.url, // writes to the val that calls this function }); console.log(result); // { success: true, action: "created", id: "...", name: "hello.txt", url: "..." }

Parameters

writeFile accepts a single object with the following properties:

ParameterTypeRequiredDescription
pathstringFile path within the val (e.g. "src/utils.ts")
contentstringThe file content
typestringFile type ("file", "http", "script", "interval", "email")
callerUrlstringPass import.meta.url to target the calling val.
valIdstringTarget val ID. Takes precedence over callerUrl if both are provided.
tokenstringVal Town API bearer token. Defaults to the VT_WRITE_TOKEN environment variable.

Return Value

On success:

{ success: true, action: "created" | "updated", id: string, // file ID name: string, // file name url: string, // link to the file on val.town }

On error:

{ success: false, error: string, // the error message (or "unknown error") }

Authentication

By default, the function looks for a VT_WRITE_TOKEN environment variable. You need a Val Town API token with write permissions. You can also pass a token directly:

await writeFile({ path: "data.json", content: JSON.stringify({ key: "value" }), type: "file", callerUrl: import.meta.url, token: "your-api-token", });