Standard Library
File System (fs)

File System (fs)

The fs module provides file system operations for reading, writing, and managing files.

Module funcs

fs.readFile()

Read the entire contents of a file:

let content = fs.readFile("data.txt");
print(content);

Parameters:

  • filename (string): Path to the file

Returns: String containing file contents, or null on error

fs.writeFile()

Write data to a file (overwrites existing content):

fs.writeFile("output.txt", "Hello, Flowa!");

Parameters:

  • filename (string): Path to the file
  • content (string): Data to write

Returns: true on success, false on error

fs.appendFile()

Append data to a file:

fs.appendFile("log.txt", "New log entry\n");

Parameters:

  • filename (string): Path to the file
  • content (string): Data to append

Returns: true on success, false on error

fs.exists()

Check if a file exists:

let exists = fs.exists("config.json");
if (exists) {
    print("File found");
}

Parameters:

  • filename (string): Path to check

Returns: true if file exists, false otherwise

Examples

Read Configuration File

if (fs.exists("config.json")) {
    let config_text = fs.readFile("config.json");
    let config = json.parse(config_text);
    print("App name: " + config["app_name"]);
} else {
    print("Config file not found");
}

Write Log File

func log_to_file(message) {
    let timestamp = "2024-12-12 10:30:00";  // Get current time
    let log_entry = "[" + timestamp + "] " + message + "\n";
    fs.appendFile("application.log", log_entry);
}
 
log_to_file("Application started");
log_to_file("User logged in");
log_to_file("Database connected");

Process Text File Line by Line

let content = fs.readFile("data.txt");
let lines = split(content, "\n");
 
let i = 0;
while (i < len(lines)) {
    let line = trim(lines[i]);
    if (len(line) > 0) {
        print("Line " + tostring(i + 1) + ": " + line);
    }
    i = i + 1;
}

Save and Load JSON Data

// Save data
let users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25}
];
 
let json_string = json.stringify(users);
fs.writeFile("users.json", json_string);
 
// Load data
if (fs.exists("users.json")) {
    let loaded_data = fs.readFile("users.json");
    let parsed_users = json.parse(loaded_data);
    print("Loaded " + tostring(len(parsed_users)) + " users");
}

Create Backup

func backup_file(filename) {
    if (!fs.exists(filename)) {
        return false;
    }
    
    let content = fs.readFile(filename);
    let backup_name = filename + ".backup";
    fs.writeFile(backup_name, content);
    
    print("Backup created: " + backup_name);
    return true;
}
 
backup_file("important.txt");

CSV File Processing

// Read CSV
let csv_content = fs.readFile("data.csv");
let lines = split(csv_content, "\n");
 
// Process each line
let i = 1;  // Skip header
while (i < len(lines)) {
    let line = lines[i];
    let fields = split(line, ",");
    
    if (len(fields) >= 3) {
        let name = fields[0];
        let email = fields[1];
        let age = fields[2];
        
        print(name + ": " + email);
    }
    
    i = i + 1;
}

Write Report

func generate_report(data) {
    let report = "=== REPORT ===\n\n";
    
    let i = 0;
    while (i < len(data)) {
        let item = data[i];
        report = report + "Item " + tostring(i + 1) + ": " + item["name"] + "\n";
        report = report + "Value: " + tostring(item["value"]) + "\n\n";
        i = i + 1;
    }
    
    report = report + "Total items: " + tostring(len(data)) + "\n";
    fs.writeFile("report.txt", report);
}
 
let data = [
    {"name": "Product A", "value": 100},
    {"name": "Product B", "value": 200}
];
 
generate_report(data);

Error Handling

Always check if files exist before reading:

let filename = "data.txt";
 
if (fs.exists(filename)) {
    let content = fs.readFile(filename);
    if (content != null) {
        print("Content: " + content);
    } else {
        print("Error reading file");
    }
} else {
    print("File not found: " + filename);
}

Best Practices

Check File Existence

// Always check before reading
if (fs.exists("config.json")) {
    let config = fs.readFile("config.json");
}

Handle Null Returns

let content = fs.readFile("data.txt");
if (content != null) {
    // Process content
} else {
    // Handle error
}

Use Append for Logs

// Append preserves existing content
fs.appendFile("audit.log", "Action performed\n");

Common Use Cases

  • Configuration files: Read JSON/text config
  • Logging: Append to log files
  • Data persistence: Save and load application data
  • Reports: Generate text reports
  • Backups: Create file backups
  • Batch processing: Process multiple files

Limitations

  • No directory operations (create/list/delete directories)
  • No file deletion
  • No file metadata (size, modification time)
  • Synchronous operations only

Next Steps