k.file
Read, write, copy, delete, and resolve URLs for site disk files
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
Server-side KScript (k.api, <script env="server">, scheduled jobs) | None (operates directly on site disk storage; separate from the versioned k.site.files CMS library) | Read, write, append, copy, rename, and delete disk files and resolve /__kb/kfile/ URLs |
Difference from the "Content → Files" menu
Content → Files (/content/files) in the admin UI manages the CMS File Library (CmsFile), accessible via k.site.files. k.file operates directly on the site's disk directory (no built-in admin file manager UI); see Admin: Files.
Quick Start
Write a text file, read its contents back, and inspect metadata and URL:
k.api.post(() => {
const info = k.file.write("test-folder/hello.txt", "hello world")
const content = k.file.read("test-folder/hello.txt")
return {
fullName: info.fullName,
size: info.size,
url: k.file.url("test-folder/hello.txt"),
content
}
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
write(fileName, content, withAuthorInfo?) | Writes or overwrites a text file | FileInfo |
writeBinary(fileName, binary, withAuthorInfo?) | Writes or overwrites a byte array (null if empty) | FileInfo | null |
read(fileName) | Reads text content (null if missing) | string | null |
readBinary(fileName) | Reads bytes by relative storage path (no /__kb/kfile/ prefix) | number[] | null |
append(fileName, content) | Appends text content (creates file if missing) | void |
exists(fileName) | Checks whether a disk file exists | boolean |
get(fileName, includeAuthor?) / load(...) | Loads file metadata by storage path or /__kb/kfile/... URL | FileInfo | null |
url(fileName) | Returns the relative web URL (/__kb/kfile/...) | string |
rename(oldName, newName) / copy(oldName, newName) | Renames or copies a file/directory (does not overwrite existing files) | void |
delete(fileName) | Deletes a disk file | void |
toValidPath(input) | Strips OS invalid path characters and replaces spaces with _ | string |
resumableUpload | Chunked resumable upload helper (details) | ResumableUpload |
| Folder & listing methods | folderFiles, subFolders, createFolder, deleteFolder, etc. | Folder Operations |
Methods & Properties
write()
Writes text content to a file. Overwrites the file if it already exists.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path |
content | string | Yes | File content |
withAuthorInfo | boolean | No | Whether to record author information; defaults to false |
Returns: FileInfo
k.api.post("write", () => {
k.file.write("test-folder/test.txt", "hello world")
const content = k.file.read("test-folder/test.txt")
return { content: content }
})writeBinary()
Writes a byte array to a file. Overwrites the file if it already exists. Used for uploaded files, downloaded payloads, generated images/PDFs, and other binary data.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path |
binary | number[] | Yes | Byte array to write |
withAuthorInfo | boolean | No | Whether to record author information; defaults to false |
Returns: FileInfo; returns null when the byte array is empty (0 bytes) or the path fails validation.
Upload security & null guards
Never interpolate an untrusted file.fileName directly into a path (on Linux/macOS, .. segments can escape the site file root). Strip path separators and .. (or generate a safe server-side filename) before calling writeBinary(), and guard both k.request.files[0] and the returned info (0-byte uploads return null).
k.api.post("upload", () => {
const file = k.request.files[0]
if (!file) {
return { error: "No file uploaded" }
}
const baseName = (file.fileName || "").split(/[\\/]/).pop()
const safeName = k.file.toValidPath(baseName).replace(/\.\./g, "")
if (!safeName || safeName === ".") {
return { error: "Invalid file name" }
}
const info = k.file.writeBinary(`uploads/${safeName}`, file.bytes)
if (!info) {
return { error: "Empty file or write failed" }
}
return { saved: info.name, size: info.size }
})read()
Reads the text content of a file; returns null if the file does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path |
Returns: string | null — Text content of the file
k.api.get("read", () => {
return k.file.read("test-folder/test.txt")
})readBinary()
Reads a file into a byte array. Returns null when the file does not exist. Pass the relative storage path (do not pass a /__kb/kfile/ URL prefix).
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File storage path |
Returns: number[] | null — File content as a byte array
k.api.post("readBinary", () => {
const bytes = [137, 80, 78, 71, 13, 10, 26, 10]
k.file.writeBinary("test-folder/sample.png", bytes)
const readBytes = k.file.readBinary("test-folder/sample.png")
return { length: readBytes ? readBytes.length : 0, bytes: readBytes }
})append()
Appends text content to a file. Creates the file if it does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path |
content | string | Yes | Content to append |
Returns: void
k.api.post("append", () => {
k.file.append("test-folder/append.txt", "appended content")
const content = k.file.read("test-folder/append.txt")
return { content: content }
})exists()
Checks whether a file exists.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path |
Returns: boolean
k.api.get("exists", () => {
return k.file.exists("test-folder/test.txt")
})get()
Gets file metadata; returns null if the file does not exist. Accepts a relative storage path or a /__kb/kfile/... relative URL.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path or /__kb/kfile/... relative URL |
includeAuthor | boolean | No | Whether to include author information; defaults to false |
Returns: FileInfo
k.api.get("get", () => {
return k.file.get("test-folder/test.txt")
})load()
Loads file metadata by relative storage path or /__kb/kfile/... relative URL; returns null if the file does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path or /__kb/kfile/... relative URL |
includeAuthor | boolean | No | Whether to include author information; defaults to false |
Returns: FileInfo
k.api.get("load", () => {
const byPath = k.file.load("test-folder/test.txt")
const byUrl = k.file.load("/__kb/kfile/test-folder/test.txt")
return { byPath, byUrl }
})url()
Gets the relative web access URL (/__kb/kfile/...) for a file.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File name or relative path |
Returns: string — Relative URL path
k.api.get("url", () => {
return k.file.url("image.jpg")
})rename()
Renames a file. Unlike write() / writeBinary(), rename() does not overwrite an existing destination file — it throws IOException if newName already exists, and throws an exception if the source oldName does not exist.
| Parameter | Type | Required | Description |
|---|---|---|---|
oldName | string | Yes | Original file path |
newName | string | Yes | New file path |
Returns: void
k.api.post("rename", () => {
const oldPath = "test-folder/old.txt"
const newPath = "test-folder/new.txt"
k.file.write(oldPath, "content")
if (k.file.exists(newPath)) {
k.file.delete(newPath)
}
k.file.rename(oldPath, newPath)
const newExists = k.file.exists(newPath)
const oldExists = k.file.exists(oldPath)
return { newExists: newExists, oldExists: oldExists }
})copy()
Copies a file or directory. Unlike write() / writeBinary(), copy() does not overwrite existing destination files — it throws IOException if the destination file already exists (and silently does nothing if oldName does not exist).
| Parameter | Type | Required | Description |
|---|---|---|---|
oldName | string | Yes | Source path |
newName | string | Yes | Destination path |
Returns: void
k.api.post("copy", () => {
const src = "test-folder/source.txt"
const dest = "test-folder/dest.txt"
k.file.write(src, "content")
if (k.file.exists(dest)) {
k.file.delete(dest)
}
k.file.copy(src, dest)
const destExists = k.file.exists(dest)
return { destExists: destExists }
})delete()
Deletes a file.
| Parameter | Type | Required | Description |
|---|---|---|---|
fileName | string | Yes | File path |
Returns: void
k.api.post("delete", () => {
k.file.write("test-folder/to-delete.txt", "content")
k.file.delete("test-folder/to-delete.txt")
const exists = k.file.exists("test-folder/to-delete.txt")
return { deleted: !exists }
})toValidPath()
Strips OS invalid path characters (System.IO.Path.GetInvalidPathChars(), which only contains \0 on Linux/macOS), collapses double spaces, and replaces spaces with _. Note: It does not strip valid filename characters such as @, nor does it sanitize or resolve .. path segments.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Input path |
Returns: string
k.api.get("toValidPath", () => {
return k.file.toValidPath("folder/my file.txt") // "folder/my_file.txt"
})TypeScript Definitions
interface FileIO {
resumableUpload: ResumableUpload;
write(fileName: string, content: string): FileInfo;
write(fileName: string, content: string, WithAuthorInfo: boolean): FileInfo;
writeBinary(fileName: string, binary: number[]): FileInfo;
writeBinary(fileName: string, binary: number[], WithAuthorInfo: boolean): FileInfo;
append(FileName: string, content: string): void;
toValidPath(input: string): string;
url(filename: string): string;
read(FileName: string): string;
readBinary(FileName: string): number[];
exists(FileName: string): boolean;
folderExists(path: string): boolean;
load(FileName: string): FileInfo;
load(FileName: string, IncludeAuthor: boolean): FileInfo;
get(FileName: string): FileInfo;
get(FileName: string, IncludeAuthor: boolean): FileInfo;
rename(oldName: string, newName: string): void;
copy(oldName: string, newName: string): void;
delete(FileName: string): void;
getAllFiles(): FileInfo[];
getAllFiles(IncludeAuthor: boolean): FileInfo[];
folderFiles(folder: string, options?: SearchFolderOptions): FileInfo[];
subFolders(folder?: string): FolderInfo[];
createFolder(Folder: string, ParentFolder: string): void;
createFolder(Folder: string): void;
renameFolder(oldFolder: string, newFolder: string): void;
deleteFolder(Folder: string): void;
}Related Docs
- Folder Operations — k.file — Directory CRUD and file listings
- k.file.resumableUpload — Chunked resumable upload
- FileInfo / SearchFolderOptions — k.file — File, folder, and search data structures
- k.site.files — CMS File Library management
- k.site — Site management