file
The file extension provides filesystem access for reading, writing, and managing files and directories.
API
| Method | Description |
|---|---|
file.read(path) | Read file contents as a string |
file.write(path, content) | Write/overwrite a file |
file.append(path, content) | Append to a file |
file.exists(path) | Check if file or directory exists |
file.delete(path) | Delete a file |
file.size(path) | Get file size in bytes |
file.isDir(path) | Check if path is a directory |
file.list(path) | List directory contents |
Reading Files
const content = file.read("/var/www/data/config.json");
const config = JSON.parse(content);
Writing Files
// Overwrite
file.write("/tmp/output.txt", "Hello, World!");
// Append
file.append("/var/log/app.log", new Date().toISOString() + " Request received\n");
File Checks
if (file.exists("/var/www/data/cache.json")) {
const cached = file.read("/var/www/data/cache.json");
print(cached);
}
const size = file.size("/var/www/uploads/photo.jpg"); // bytes
const isDirectory = file.isDir("/var/www/uploads"); // true
Directory Listing
const files = file.list("/var/www/uploads");
// ["photo.jpg", "document.pdf", "data.csv"]
// Filter by extension
const images = files.filter(f => f.endsWith(".jpg") || f.endsWith(".png"));
Deleting Files
file.delete("/tmp/old-cache.json");
JSON File Storage
const DATA_FILE = "/var/www/data/todos.json";
// Read
const todos = file.exists(DATA_FILE) ? JSON.parse(file.read(DATA_FILE)) : [];
// Add
todos.push({ id: todos.length + 1, title: "New task", done: false });
// Save
file.write(DATA_FILE, JSON.stringify(todos, null, 2));