File Operations in GoloScript

This guide covers file and directory operations in Golo-Script.

Basic Operations

Golo-Script provides built-in functions for file and directory manipulation:

Reading Files

# Read the complete content of a file
let content = readFile("path/to/file.txt")
println(content)

Writing Files

# Write content to a file (overwrites existing file)
writeFile("output.txt", "Hello, Golo!\n")

Appending to Files

# Append content to the end of an existing file
appendFile("log.txt", "New log entry\n")

Deleting Files

# Delete a file or empty directory
deleteFile("temp.txt")

File Information

The fileInfo() function returns an object with information about a file:

let info = fileInfo("myfile.txt")

# Get the file name
println("Name:", info: name())

# Get the size in bytes
println("Size:", info: size(), "bytes")

# Check if it's a directory
if info: isDir() {
  println("It's a directory")
} else {
  println("It's a file")
}

# Get the modification time
println("Modified:", info: modTime())

Checking File Existence

if fileExists("config.json") {
  println("File exists")
} else {
  println("File does not exist")
}

Directory Operations

Creating a Directory

# Create a new directory
mkDir("new_directory")

Listing Directory Contents

# Get list of files and directories
let files = listDir("my_directory")

foreach file in files {
  println("  -", file)
}

Complete Example

# Create directory structure
mkDir("project")

# Create multiple files
writeFile("project/readme.txt", "Project documentation")
writeFile("project/config.txt", "Configuration")
writeFile("project/data.txt", "Data")

# List all files
let files = listDir("project")
println("Files in project:", files)

# Cleanup
deleteFile("project/readme.txt")
deleteFile("project/config.txt")
deleteFile("project/data.txt")
deleteFile("project")

Current Script Directory

Golo-Script provides two functions to get the directory of the currently executing script:

Relative Path

# Get the directory of the current script (relative path)
let dir = currentDir()
println("Script directory:", dir)

Absolute Path

# Get the absolute directory of the current script
let absDir = currentAbsDir()
println("Script absolute directory:", absDir)

Use Case: Loading Files Relative to the Script

This is useful when your script needs to read files located next to it, regardless of where the script is launched from:

# Read a config file located next to the script
let configPath = currentAbsDir() + "/config.json"
let config = readFile(configPath)

Error Handling

It’s important to handle errors during file operations, as they can fail for various reasons (file not found, insufficient permissions, etc.).

Safe Reading

function safeReadFile = |path| {
  try {
    let content = readFile(path)
    println("File content:")
    println(content)
    return content
  } catch (e) {
    println("Error reading file:", e)
    return null
  }
}

# Usage
safeReadFile("existing_file.txt")
safeReadFile("nonexistent_file.txt")  # Won't stop the program

Safe Writing with Validation

function safeWriteFile = |path, content| {
  try {
    # Validate inputs
    require(path, "File path is required")
    require(content, "Content is required")

    writeFile(path, content)
    println("Successfully wrote to:", path)
    return true
  } catch (e) {
    println("Error writing file:", e)
    return false
  }
}

Safe Directory Creation

function ensureDir = |path| {
  try {
    mkDir(path)
    println("Created directory:", path)
    return true
  } catch (e) {
    # Check if directory already exists
    try {
      if fileExists(path) {
        let info = fileInfo(path)
        if info: isDir() {
          println("Directory already exists:", path)
          return true
        } else {
          println("Error: Path exists but is not a directory")
          return false
        }
      } else {
        println("Error creating directory:", e)
        return false
      }
    } catch (checkError) {
      println("Error checking directory:", checkError)
      return false
    }
  }
}

Operations with Cleanup (finally)

The finally block ensures cleanup code always executes, even when errors occur:

function processFileWithCleanup = |inputPath, outputPath| {
  var tempFile = null

  try {
    # Read input file
    let content = readFile(inputPath)
    println("Read", len(content), "characters from", inputPath)

    # Create temporary file
    tempFile = "temp_processing.txt"
    writeFile(tempFile, content)
    println("Created temporary file:", tempFile)

    # Process content
    let processed = content

    # Write output
    writeFile(outputPath, processed)
    println("Successfully processed to:", outputPath)

  } catch (e) {
    println("Processing failed:", e)
    throw e

  } finally {
    # Always cleanup temporary file
    if isNotNull(tempFile) and fileExists(tempFile) {
      try {
        deleteFile(tempFile)
        println("Cleaned up temporary file")
      } catch (cleanupError) {
        println("Warning: Could not delete temp file:", cleanupError)
      }
    }
  }
}

Safe Directory Listing

function safeListDir = |path| {
  try {
    if not fileExists(path) {
      throw raise("Directory does not exist: " + path)
    }

    let info = fileInfo(path)
    if not info: isDir() {
      throw raise("Path is not a directory: " + path)
    }

    let files = listDir(path)
    println("Files in", path + ":")
    foreach file in files {
      println("  -", file)
    }
    return files

  } catch (e) {
    println("Error listing directory:", e)
    return array[]
  }
}

Best Practices

1. Always Handle Errors

Never assume a file operation will succeed. Use try/catch blocks to handle potential errors.

2. Validate Inputs

Always check that paths and content are valid before performing operations:

require(filePath, "File path cannot be null")
require(content, "Content cannot be null")

3. Clean Up Resources

Use finally blocks to ensure temporary files and other resources are cleaned up, even when errors occur.

4. Check Existence Before Deletion

if fileExists(path) {
  deleteFile(path)
}

5. Use Appropriate Relative or Absolute Paths

# Relative path (from current working directory)
writeFile("data/output.txt", content)

# Absolute path
writeFile("/tmp/output.txt", content)

6. Handle Edge Cases

function displayFileInfo = |path| {
  try {
    if not fileExists(path) {
      throw raise("File not found: " + path)
    }

    let info = fileInfo(path)
    println("File:", info: name())
    println("  Size:", info: size(), "bytes")
    println("  Type:", if info: isDir() { "Directory" } else { "File" })
    println("  Modified:", info: modTime())

  } catch (e) {
    println("Error getting file info:", e)
  }
}

Available Functions

File Functions

Function Description
readFile(path) Reads and returns the complete content of a file
writeFile(path, content) Writes content to a file (overwrites if exists)
appendFile(path, content) Appends content to the end of a file
deleteFile(path) Deletes a file or empty directory
fileExists(path) Checks if a file or directory exists
fileInfo(path) Returns an object with file information
currentDir() Returns the directory of the currently executing script (relative path)
currentAbsDir() Returns the absolute directory of the currently executing script

FileInfo Methods

Method Description
name() Returns the file name
size() Returns the size in bytes
isDir() Returns true if it’s a directory
modTime() Returns the last modification time

Directory Functions

Function Description
mkDir(path) Creates a new directory
listDir(path) Returns an array of files and directories in the specified directory

Β© 2026 GoloScript Project | Built with Gu10berg

Subscribe: πŸ“‘ RSS | βš›οΈ Atom