Filesystem Access

The fs module provides functions for interacting with the file system.

Functions can be individually imported and directly accessed using the named import syntax:

import { readlink, popen } from 'fs';

let dest = readlink('/sys/class/net/eth0');
let proc = popen('ps ww');

Alternatively, the module namespace can be imported using a wildcard import statement:

import * as fs from 'fs';

let dest = fs.readlink('/sys/class/net/eth0');
let proc = fs.popen('ps ww');

Additionally, the filesystem module namespace may also be imported by invoking the ucode interpreter with the -lfs switch.

Classes

fs.dir

Represents a handle for interacting with a directory opened by opendir().

fs.file

Represents a handle for interacting with a file opened by one of the file open functions.

fs.proc

Represents a handle for interacting with a program launched by popen().

Methods

access(path, modeopt) → {boolean}nullable

Checks the accessibility of a file or directory.

The optional modes argument specifies the access modes which should be checked. A file is only considered accessible if all access modes specified in the modes argument are possible.

The following modes are recognized:

ModeDescription
"r"Tests whether the file is readable.
"w"Tests whether the file is writable.
"x"Tests whether the file is executable.
"f"Tests whether the file exists.

Returns true if the given path is accessible or false when it is not.

Returns null if an error occurred, e.g. due to inaccessible intermediate path components, invalid path arguments etc.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

modenumber(optional, default: "f")

Optional access mode.

Returns: boolean
Example
// Check file read and write accessibility
const isAccessible = access('path/to/file', 'rw');

// Check execute permissions
const mayExecute = access('/usr/bin/example', 'x');

basename(path) → {string}nullable

Retrieves the base name of a path.

Returns the base name component of the specified path.

Returns null if the path argument is not a string.

Parameters:
NameTypeDescription
pathstring

The path to extract the base name from.

Returns: string
Example
// Get the base name of a path
const baseName = basename('/path/to/file.txt');

chdir(path) → {boolean}nullable

Changes the current working directory to the specified path.

Returns true if the permission change was successful.

Returns null if an error occurred, e.g. due to insufficient permissions or invalid arguments.

Parameters:
NameTypeDescription
pathstring

The path to the new working directory.

Returns: boolean
Example
// Change the current working directory
chdir('new-directory');

chmod(path, mode) → {boolean}nullable

Changes the permission mode bits of a file or directory.

Returns true if the permission change was successful.

Returns null if an error occurred, e.g. due to insufficient permissions or invalid arguments.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

modenumber

The new mode (permissions).

Returns: boolean
Example
// Change the mode of a file
chmod('path/to/file', 0o644);

chown(path, uidopt, gidopt) → {boolean}nullable

Changes the owner and group of a file or directory.

The user and group may be specified either as uid or gid number respectively, or as a string containing the user or group name, in which case it is resolved to the proper uid/gid first.

If either the user or group parameter is omitted or given as -1, it is not changed.

Returns true if the ownership change was successful.

Returns null if an error occurred or if a user/group name cannot be resolved to a uid/gid value.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

uidnumber | string(optional, default: -1)

The new owner's user ID. When given as number, it is used as-is, when given as string, the user name is resolved to the corresponding uid first.

gidnumber | string(optional, default: -1)

The new group's ID. When given as number, it is used as-is, when given as string, the group name is resolved to the corresponding gid first.

Returns: boolean
Example
// Change the owner of a file
chown('path/to/file', 1000);

// Change the group of a directory
chown('/htdocs/', null, 'www-data');

dirname(path) → {string}nullable

Retrieves the directory name of a path.

Returns the directory name component of the specified path.

Returns null if the path argument is not a string.

Parameters:
NameTypeDescription
pathstring

The path to extract the directory name from.

Returns: string
Example
// Get the directory name of a path
const directoryName = dirname('/path/to/file.txt');

error() → {string}nullable

Query error information.

Returns a string containing a description of the last occurred error or null if there is no error information.

Returns: string
Example
// Trigger file system error
unlink('/path/does/not/exist');

// Print error (should yield "No such file or directory")
print(error(), "\n");

fdopen(fd, modeopt) → {Object}

Associates a file descriptor number with a file handle object.

The mode argument controls how the file handle object is opened and must match the open mode of the underlying descriptor.

It may be set to one of the following values:

ModeDescription
"r"Opens a file stream for reading. The file descriptor must be valid and opened in read mode.
"w"Opens a file stream for writing. The file descriptor must be valid and opened in write mode.
"a"Opens a file stream for appending. The file descriptor must be valid and opened in write mode.
"r+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"w+"Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode.
"a+"Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode.

Returns the file handle object associated with the file descriptor.

Parameters:
NameTypeDescription
fdnumber

The file descriptor.

modestring(optional, default: "r")

The open mode.

Returns: Object
Example
// Associate file descriptors of stdin and stdout with handles
const stdinHandle = fdopen(0, 'r');
const stdoutHandle = fdopen(1, 'w');

getcwd() → {string}nullable

Retrieves the current working directory.

Returns a string containing the current working directory path.

Returns null if an error occurred.

Returns: string
Example
// Get the current working directory
const cwd = getcwd();

lsdir(path) → {string[]}nullable

Lists the content of a directory.

Returns a sorted array of the names of files and directories in the specified directory.

Returns null if an error occurred, e.g. if the specified directory cannot be opened.

Parameters:
NameTypeDescription
pathstring

The path to the directory.

Returns: string[]
Example
// List the content of a directory
const fileList = lsdir('/path/to/directory');

lstat(path) → {FileStatResult}nullable

Retrieves information about a file or directory, without following symbolic links.

Returns an object containing information about the file or directory.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Example
// Get information about a directory
const dirInfo = lstat('path/to/directory');

mkdir(path) → {boolean}nullable

Creates a new directory.

Returns true if the directory was successfully created.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the new directory.

Returns: boolean
Example
// Create a directory
mkdir('path/to/new-directory');

mkstemp(templateopt) → {file}nullable

Creates a unique, ephemeral temporary file.

Creates a new temporary file, opens it in read and write mode, unlinks it and returns a file handle object referring to the yet open but deleted file.

Upon closing the handle, the associated file will automatically vanish from the system.

The optional path template argument may be used to override the path and name chosen for the temporary file. If the path template contains no path element, /tmp/ is prepended, if it does not end with XXXXXX, then * .XXXXXX is appended to it. The XXXXXX sequence is replaced with a random value ensuring uniqueness of the temporary file name.

Returns a file handle object referring to the ephemeral file on success.

Returns null if an error occurred, e.g. on insufficient permissions or inaccessible directory.

Parameters:
NameTypeDescription
templatestring(optional, default: "/tmp/XXXXXX")

The path template to use when forming the temporary file name.

Returns: file
Example
// Create a unique temporary file in the current working directory
const tempFile = mkstemp('./data-XXXXXX');

open(path, modeopt, permopt) → {file}nullable

Opens a file.

The mode argument specifies the way the file is opened, it may start with one of the following values:

ModeDescription
"r"Opens a file for reading. The file must exist.
"w"Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a"Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created.
"r+"Opens a file for both reading and writing. The file must exist.
"w+"Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created.
"a+"Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created.

Additionally, the following flag characters may be appended to the mode value:

FlagDescription
"x"Opens a file for exclusive creation. If the file exists, the open call fails.
"e"Opens a file with the O_CLOEXEC flag set, ensuring that the file descriptor is closed on exec calls.

If the mode is one of "w…" or "a…", the permission argument controls the filesystem permissions bits used when creating the file.

Returns a file handle object associated with the opened file.

Parameters:
NameTypeDescription
pathstring

The path to the file.

modestring(optional, default: "r")

The file opening mode.

permnumber(optional, default: 0o666)

The file creation permissions (for modes w… and a…)

Returns: file
Example
// Open a file in read-only mode
const fileHandle = open('file.txt', 'r');

opendir(path) → {dir}nullable

Opens a directory and returns a directory handle associated with the open directory descriptor.

Returns a director handle referring to the open directory.

Returns null if an error occurred.

Parameters:
NameTypeDescription
pathstring

The path to the directory.

Returns: dir
Example
// Open a directory
const directory = opendir('path/to/directory');

pipe() → {file[]}nullable

Creates a pipe and returns file handle objects associated with the read- and write end of the pipe respectively.

Returns a two element array containing both a file handle object open in read mode referring to the read end of the pipe and a file handle object open in write mode referring to the write end of the pipe.

Returns null if an error occurred.

Returns: file[]
Example
// Create a pipe
const pipeHandles = pipe();
pipeHandles[1].write("Hello world\n");
print(pipeHandles[0].read("line"));

popen(command, modeopt) → {proc}nullable

Starts a process and returns a handle representing the executed process.

The handle will be connected to the process stdin or stdout, depending on the value of the mode argument.

The mode argument may be either "r" to open the process for reading (connect to its stdin) or "w" to open the process for writing (connect to its stdout).

The mode character "r" or "w" may be optionally followed by "e" to apply the FD_CLOEXEC flag onto the open descriptor.

Returns a process handle referring to the executed process.

Returns null if an error occurred.

Parameters:
NameTypeDescription
commandstring

The command to be executed.

modestring(optional, default: "r")

The open mode of the process handle.

Returns: proc
Example
// Open a process
const process = popen('command', 'r');

readfile(path, limitopt) → {string}nullable

Reads the content of a file, optionally limited to the given amount of bytes.

Returns a string containing the file contents.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file.

limitnumber(optional)

Number of bytes to limit the result to. When omitted, the entire content is returned.

Returns: string
Example
// Read first 100 bytes of content
const content = readfile('path/to/file', 100);

// Read entire file content
const content = readfile('path/to/file');

Reads the target path of a symbolic link.

Returns a string containing the target path.

Returns null if an error occurred.

Parameters:
NameTypeDescription
pathstring

The path to the symbolic link.

Returns: string
Example
// Read the value of a symbolic link
const targetPath = readlink('symbolicLink');

realpath(path) → {string}nullable

Resolves the absolute path of a file or directory.

Returns a string containing the resolved path.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Returns: string
Example
// Resolve the absolute path of a file
const absolutePath = realpath('path/to/file', 'utf8');

rename(oldPath, newPath) → {boolean}nullable

Renames or moves a file or directory.

Returns true if the rename operation was successful.

Returns null if an error occurred.

Parameters:
NameTypeDescription
oldPathstring

The current path of the file or directory.

newPathstring

The new path of the file or directory.

Returns: boolean
Example
// Rename a file
rename('old-name.txt', 'new-name.txt');

rmdir(path) → {boolean}nullable

Removes the specified directory.

Returns true if the directory was successfully removed.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the directory to be removed.

Returns: boolean
Example
// Remove a directory
rmdir('path/to/directory');

stat(path) → {FileStatResult}nullable

Retrieves information about a file or directory.

Returns an object containing information about the file or directory.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file or directory.

Example
// Get information about a file
const fileInfo = stat('path/to/file');

Creates a new symbolic link.

Returns true if the symlink was successfully created.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
targetstring

The target of the symbolic link.

pathstring

The path of the symbolic link.

Returns: boolean
Example
// Create a symbolic link
symlink('target', 'path/to/symlink');

Removes the specified file or symbolic link.

Returns true if the unlink operation was successful.

Returns null if an error occurred, e.g. due to inexistent path.

Parameters:
NameTypeDescription
pathstring

The path to the file or symbolic link.

Returns: boolean
Example
// Remove a file
unlink('path/to/file');

writefile(path, data, limitopt) → {number}nullable

Writes the given data to a file, optionally truncated to the given amount of bytes.

In case the given data is not a string, it is converted to a string before being written into the file. String values are written as-is, integer and double values are written in decimal notation, boolean values are written as true or false while arrays and objects are converted to their JSON representation before being written into the file. The null value is represented by an empty string so writefile(…, null) would write an empty file. Resource values are written in the form <type address>, e.g. <fs.file 0x7f60f0981760>.

If resource, array or object values contain a tostring() function in their prototypes, then this function is invoked to obtain an alternative string representation of the value.

If a file already exists at the given path, it is truncated. If no file exists, it is created with default permissions 0o666 masked by the currently effective umask.

Returns the number of bytes written.

Returns null if an error occurred, e.g. due to insufficient permissions.

Parameters:
NameTypeDescription
pathstring

The path to the file.

data*

The data to be written.

limitnumber(optional)

Truncates the amount of data to be written to the specified amount of bytes. When omitted, the entire content is written.

Returns: number
Example
// Write string to a file
const bytesWritten = writefile('path/to/file', 'Hello, World!');

// Write object as JSON to a file and limit to 1024 bytes at most
const obj = { foo: "Hello world", bar: true, baz: 123 };
const bytesWritten = writefile('debug.txt', obj, 1024);

Type Definitions

FileStatResult: Object

Properties
NameTypeDescription
devObject

The device information.

Properties
NameTypeDescription
majornumber

The major device number.

minornumber

The minor device number.

permObject

The file permissions.

Properties
NameTypeDescription
setuidboolean

Whether the setuid bit is set.

setgidboolean

Whether the setgid bit is set.

stickyboolean

Whether the sticky bit is set.

user_readboolean

Whether the file is readable by the owner.

user_writeboolean

Whether the file is writable by the owner.

user_execboolean

Whether the file is executable by the owner.

group_readboolean

Whether the file is readable by the group.

group_writeboolean

Whether the file is writable by the group.

group_execboolean

Whether the file is executable by the group.

other_readboolean

Whether the file is readable by others.

other_writeboolean

Whether the file is writable by others.

other_execboolean

Whether the file is executable by others.

inodenumber

The inode number.

modenumber

The file mode.

nlinknumber

The number of hard links.

uidnumber

The user ID of the owner.

gidnumber

The group ID of the owner.

sizenumber

The file size in bytes.

blksizenumber

The block size for file system I/O.

blocksnumber

The number of 512-byte blocks allocated for the file.

atimenumber

The timestamp when the file was last accessed.

mtimenumber

The timestamp when the file was last modified.

ctimenumber

The timestamp when the file status was last changed.

typestring

The type of the file ("directory", "file", etc.).