Skip to main content

fs File System

fs is Alia's standard library file system module, providing operations such as reading, writing, copying, renaming, and deleting files.

Importing the Module​

import 'fs' as fs ~ import as a variable
import 'fs' ~ import into scope

Methods​

read​

read reads the contents of a file and returns a String.

const content = fs.read 'hello.txt'
print content

Throws an error if the file does not exist.

write​

write writes content to a file, automatically creating the target directory if it does not exist.

fs.write 'Hello, Alia!' to 'output.txt'

rename​

rename renames or moves a file.

fs.rename 'old.txt' to 'new.txt'

remove​

remove deletes a file, throwing an error if the file does not exist.

fs.remove 'temp.txt'

copy​

copy copies a file, automatically creating the target directory if it does not exist.

fs.copy 'source.txt' to 'backup.txt'

stat​

stat retrieves file information and returns an Object with the following properties:

PropertyTypeDescription
sizeNumberFile size (bytes)
isFileBooleanWhether it is a file
isDirectoryBooleanWhether it is a directory
modifiedStringLast modified time (ISO 8601)
const info = fs.stat 'hello.txt'
print info.size ~ prints the file size
print info.isFile ~ prints true
print info.isDirectory ~ prints false

exist​

exist checks whether a file exists and returns a Boolean.

if fs.exist 'config.json' {
const config = fs.read 'config.json'
print config
}

list​

list enumerates the direct children of a directory and returns a sorted Array. Children include both files and directories; directories carry no marker.

const names = fs.list 'src'
each name in names {
print name
}

listRecursive​

listRecursive walks a directory recursively and returns a sorted Array of paths relative to the given path. Directory entries end with /, and the separator is always / regardless of the host platform.

const files = fs.listRecursive '.'
each rel in files {
if rel.endsWith '.alia' {
print rel
}
}

The fixed ordering and separator are deliberate: the compiler walks source trees, the Analyzer builds a workspace index, and ModSpace packs releases — all of them need results that agree across targets and across runs.

Both methods throw FS_LIST_FAILED when the path does not exist, is not a directory, or is not readable.

Example Code​

import 'fs' as fs

const demoPath = '/tmp/demo.txt'
const copyPath = '/tmp/demo_copy.txt'
const renamedPath = '/tmp/demo_renamed.txt'

~ Write a file
fs.write 'Hello, Alia!' to demoPath

~ Read the file
const content = fs.read demoPath
print content

~ Check whether the file exists
assert fs.exist demoPath error 'The file should exist'

~ Get file information
const info = fs.stat demoPath
print info.size

~ Copy the file
fs.copy demoPath to copyPath

~ Rename the file
fs.rename copyPath to renamedPath

~ Delete the files
fs.remove demoPath
fs.remove renamedPath

Next Steps​