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:
Mode | Description |
---|---|
"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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or directory. |
mode | number | (optional, default: "f" )Optional access mode. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to extract the base name from. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the new working directory. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or directory. |
mode | number | The new mode (permissions). |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or directory. |
uid | number | | (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. |
gid | number | | (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. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to extract the directory name from. |
// 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.
// 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:
Mode | Description |
---|---|
"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.
Name | Type | Description |
---|---|---|
fd | number | The file descriptor. |
mode | string | (optional, default: "r" )The open mode. |
// 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.
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the directory. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or directory. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the new directory. |
// 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.
Name | Type | Description |
---|---|---|
template | string | (optional, default: "/tmp/XXXXXX" )The path template to use when forming the temporary file name. |
// 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:
Mode | Description |
---|---|
"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:
Flag | Description |
---|---|
"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.
Name | Type | Description |
---|---|---|
path | string | The path to the file. |
mode | string | (optional, default: "r" )The file opening mode. |
perm | number | (optional, default: 0o666 )The file creation permissions (for modes |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the directory. |
// 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.
// 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.
Name | Type | Description |
---|---|---|
command | string | The command to be executed. |
mode | string | (optional, default: "r" )The open mode of the process handle. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file. |
limit | number | (optional) Number of bytes to limit the result to. When omitted, the entire content is returned. |
// Read first 100 bytes of content
const content = readfile('path/to/file', 100);
// Read entire file content
const content = readfile('path/to/file');
readlink(path) → {string}nullable
Reads the target path of a symbolic link.
Returns a string containing the target path.
Returns null
if an error occurred.
Name | Type | Description |
---|---|---|
path | string | The path to the symbolic link. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or directory. |
// 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.
Name | Type | Description |
---|---|---|
oldPath | string | The current path of the file or directory. |
newPath | string | The new path of the file or directory. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the directory to be removed. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or directory. |
// Get information about a file
const fileInfo = stat('path/to/file');
symlink(target, path) → {boolean}nullable
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.
Name | Type | Description |
---|---|---|
target | string | The target of the symbolic link. |
path | string | The path of the symbolic link. |
// Create a symbolic link
symlink('target', 'path/to/symlink');
unlink(path) → {boolean}nullable
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.
Name | Type | Description |
---|---|---|
path | string | The path to the file or symbolic link. |
// 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.
Name | Type | Description |
---|---|---|
path | string | The path to the file. |
data | * | The data to be written. |
limit | number | (optional) Truncates the amount of data to be written to the specified amount of bytes. When omitted, the entire content is written. |
// 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
PropertiesName | Type | Description | |||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dev | Object | The device information. Properties
| |||||||||||||||||||||||||||||||||||||||
perm | Object | The file permissions. Properties
| |||||||||||||||||||||||||||||||||||||||
inode | number | The inode number. | |||||||||||||||||||||||||||||||||||||||
mode | number | The file mode. | |||||||||||||||||||||||||||||||||||||||
nlink | number | The number of hard links. | |||||||||||||||||||||||||||||||||||||||
uid | number | The user ID of the owner. | |||||||||||||||||||||||||||||||||||||||
gid | number | The group ID of the owner. | |||||||||||||||||||||||||||||||||||||||
size | number | The file size in bytes. | |||||||||||||||||||||||||||||||||||||||
blksize | number | The block size for file system I/O. | |||||||||||||||||||||||||||||||||||||||
blocks | number | The number of 512-byte blocks allocated for the file. | |||||||||||||||||||||||||||||||||||||||
atime | number | The timestamp when the file was last accessed. | |||||||||||||||||||||||||||||||||||||||
mtime | number | The timestamp when the file was last modified. | |||||||||||||||||||||||||||||||||||||||
ctime | number | The timestamp when the file status was last changed. | |||||||||||||||||||||||||||||||||||||||
type | string | The type of the file ("directory", "file", etc.). |