Contents

file

The file module provides functionality for working with files. It is written in Koji (std/file.kj), on the C library of the system: File is an opaque type with a drop method, which closes it.

Functions

  • open(path: string, mode: Mode) -> Result[File, FileError]
    Opens the file at path in the specified mode:

    type Mode = {
        Read // read
        Write // write (overwrites existing content)
        Append // write at the end
    }

    With import file, the modes are file.Read, file.Write and file.Append. With import { Mode } from 'file', they can be written Read, Write and Append. Since the mode is a sum type, an invalid mode does not compile.

  • remove(path: string) -> Result[void, FileError]
    Removes the file at path. It does not remove a directory: that gives Err(IsDirectory(path)).

    import file
    
    match (file.remove('old-notes.txt')) {
        Ok(_) => print('removed')
        Err(NotFound(path)) => print(`${path} was already gone`)
        Err(error) => print(error)
    }
  • removeDir(path: string) -> Result[void, FileError]
    Removes the directory at path, which must be empty.

  • setPermissions(path: string, mode: int) -> Result[void, FileError]
    Sets the permissions of the file at path, as the bits of Unix (0x1ED is rwxr-xr-x, 0755 in octal: an executable).

Directories

  • list(path: string) -> Result[string[], FileError]
    The names of the entries (files and directories) in the directory at path, sorted. The names do not include path; use path.join to build full paths.

  • exists(path: string) -> boolean
    Whether a file or directory exists at path.

  • createDir(path: string) -> Result[void, FileError]
    Creates the directory at path, along with any missing parent directories. If it already exists, nothing changes.

Methods of File

  • read() -> Result[string, FileError]
    Reads the entire contents of the file. The file must have been opened with Read.

  • write(text: string) -> Result[void, FileError]
    Writes text to the file. The file must have been opened with Write or Append.

  • readBytes() -> Result[byte[], FileError]
    Reads the entire contents of the file as bytes, whatever they are (an image, a program, text in another encoding). The file must have been opened with Read.

  • writeBytes(bytes: byte[]) -> Result[void, FileError]
    Writes the bytes to the file. The file must have been opened with Write or Append.

  • close() -> void
    Closes the file. It consumes the variable: using it afterwards is a compile error.

A File is move-only: it cannot be copied, only moved, and it is closed automatically when its owner goes out of scope (see Values and Memory). So close() is only needed to close a file earlier.

Reading a file opened for writing, or writing to a file opened for reading, is a bug: it panics.

Errors

type FileError = {
    NotFound(path: string)
    PermissionDenied(path: string)
    IsDirectory(path: string)
    InvalidUtf8(path: string) // the content is not valid text
    Io(path: string, message: string) // any other failure of the operating system
}

Printing an error shows a readable message, also available as error.display():

match (file.open('missing.txt', file.Read)) {
    Ok(f) => print(f.read())
    Err(error) => print(error) // file 'missing.txt' not found
}

Example

import file

match (file.open('notes.txt', file.Write)) {
    Ok(f) => {
        f.write('Hello world!')

        f.close()
    }
    Err(error) => print(error)
}

match (file.open('notes.txt', file.Read)) {
    Ok(f) => {
        match (f.read()) {
            Ok(content) => print(content)
            Err(error) => print(error)
        }

        f.close()
    }
    Err(NotFound(path)) => print(`${path} does not exist`)
    Err(error) => print(error)
}

With the ? operator (see Error Handling), inside a function:

import file

function readNotes(): Result[string, file.FileError] {
    immut f = file.open('notes.txt', file.Read)?
    immut content = f.read()?

    f.close()

    return Ok(content)
}

Edit this page on GitHub