Skip to content

k.file ​

Read, write, copy, delete, and resolve URLs for site disk files

Execution ContextPrerequisitesTypical 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:

js
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 / PropertyDescriptionReturns
write(fileName, content, withAuthorInfo?)Writes or overwrites a text fileFileInfo
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 existsboolean
get(fileName, includeAuthor?) / load(...)Loads file metadata by storage path or /__kb/kfile/... URLFileInfo | 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 filevoid
toValidPath(input)Strips OS invalid path characters and replaces spaces with _string
resumableUploadChunked resumable upload helper (details)ResumableUpload
Folder & listing methodsfolderFiles, subFolders, createFolder, deleteFolder, etc.Folder Operations

Methods & Properties ​

write() ​

Writes text content to a file. Overwrites the file if it already exists.

ParameterTypeRequiredDescription
fileNamestringYesFile path
contentstringYesFile content
withAuthorInfobooleanNoWhether to record author information; defaults to false

Returns: FileInfo

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path
binarynumber[]YesByte array to write
withAuthorInfobooleanNoWhether 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).

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path

Returns: string | null — Text content of the file

js
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).

ParameterTypeRequiredDescription
fileNamestringYesFile storage path

Returns: number[] | null — File content as a byte array

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path
contentstringYesContent to append

Returns: void

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path

Returns: boolean

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path or /__kb/kfile/... relative URL
includeAuthorbooleanNoWhether to include author information; defaults to false

Returns: FileInfo

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path or /__kb/kfile/... relative URL
includeAuthorbooleanNoWhether to include author information; defaults to false

Returns: FileInfo

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile name or relative path

Returns: string — Relative URL path

js
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.

ParameterTypeRequiredDescription
oldNamestringYesOriginal file path
newNamestringYesNew file path

Returns: void

js
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).

ParameterTypeRequiredDescription
oldNamestringYesSource path
newNamestringYesDestination path

Returns: void

js
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.

ParameterTypeRequiredDescription
fileNamestringYesFile path

Returns: void

js
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.

ParameterTypeRequiredDescription
inputstringYesInput path

Returns: string

js
k.api.get("toValidPath", () => {
    return k.file.toValidPath("folder/my file.txt") // "folder/my_file.txt"
})

TypeScript Definitions ​

ts
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;
}