writeFile
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
Viewing readonly version of main branch: v246View latest version
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.
import { writeFile } from "https://esm.town/v/nbbaier/writeFile/index.ts";
const result = await writeFile({
path: "hello.txt",
content: "Hello, world!",
type: "file",
});
console.log(result);
// { success: true, action: "created", id: "...", name: "hello.txt", url: "..." }
writeFile accepts a single object with the following properties:
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | ✅ | File path within the val (e.g. "src/utils.ts") |
content | string | ✅ | The file content |
type | string | ✅ | File type ("file", "http", "script", "interval", "email") |
valId | string | ❌ | Target val ID. Defaults to the val that imports this module. |
token | string | ❌ | Val Town API bearer token. Defaults to the VT_WRITE_TOKEN environment variable. |
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, the function throws.
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",
token: "your-api-token",
});