Skip to main content

Files API

Files API exists to provide limited access to filesystem for scripts. Te be precise, it only allows to interact with files in scripts/{ScriptName} directory.

For example, if your script name is MyScript, all files you can create and access from API, are files in the scripts/MyScript directory.

Usage

scripts/MyScript.js
const logsDir = file("logs") // This file object points to scripts/MyScript/logs directory
logsDir.mkdirs() // Create directory if it doesn't exist
const logFile = logsDir.resolve("latest.log") // scripts/MyScript/logs/latest.log file

const config = file("config.json") // This file object points to scripts/MyScript/config.json file

if (!config.exists()) { // This will check if config doesn't exist
config.write("{}") // And create it in that case
logFile.append("Config file created\n") // Append text to log file
}

const cfg = JSON.parse(config.read()) // This will read file content and parse it as JSON

logFile.append("Config loaded successfully\n") // And again, writing logs

There are many ways of passing file path to file(...path: string[]) function. You can pass it as a single string, or as multiple arguments:

file("configs/main.json")
file("configs", "main.json")
file("configs/custom/main.json")
file("configs", "custom/main.json")
file("configs", "custom", "main.json")
file("configs/test/../main.json") // This will normalize path to "configs/main.json"

// And so on...

Script directory (e.g. scripts/MyScript) is always used as a root directory. You can't access files outside of script directory.

Trying to escape script directory will result in error:

file("../config.json") // This will throw an error

Reference

Fields

NameTypeDescription
pathstringFile path in normalized from, e.g. "configs/main.json"
segmentsstringFile path segment array, e.g. ["configs", "main.json"]

Note, that these fields are read-only. Modification of these fields will not affect file object.

Methods

DefinitionDescription
resolve(...path: string[]): FileResolve relatively located file. E.g. file("configs").resolve("main.json")
exists(): booleanCheck if file/directory exists
isDir(): booleanCheck if file object pointing to a directory
isFile(): booleanCheck if file object pointing to a file
read(): stringRead file contents to a string
write(content: string): voidWrite file contents (will create file if it doesn't exist)
append(content: string): voidAppend content to file (will create file if it doesn't exist)
mkdirs()Create directory pointed on by file object (will also create parent directories)
delete(recursive?: boolean): voidDelete file or directory (will delete recursively if recursive is true)
listFiles(): string[]List names for files (and only files) located in specified directory
listDirs(): string[]List names for directories (and only directories) located in specified directory