Perfect brings file system operations into your sever-side Swift environments to control how data is stored and retrieved in an accessible way.
First, ensure the PerfectLib
is imported in your Swift file:
import PerfectLib
You are now able to use the Dir
object to query and manipulate the file system.
Specify the absolute or relative path to the directory:
let thisDir = Dir("/path/to/directory/")
Use the exists
method to return a Boolean value.
let thisDir = Dir("/path/to/directory/")
thisDir.exists
name
returns the name of the object's directory. Note that this is different from the "path".
thisDir.name
parentDir
returns a Dir
object representing the current directory object's parent. Returns nil if there is no parent.
let thisDir = Dir("/path/to/directory/")
let parent = thisDir.parentDir
path
returns the path to the current directory.
let thisDir = Dir("/path/to/directory/")
let path = thisDir.path
perms
returns the UNIX style permissions for the directory as a PermissionMode
object.
thisDir.perms
For example:
print(thisDir.perms)
>> PermissionMode(rawValue: 29092)
create
creates the directory using the provided permissions. All directories along the path will be created if needed.
The following will create a new directory with the default permissions (Owner: read-write-execute, Group and Everyone: read-execute.
let newDir = Dir("/path/to/directory/newDirectory")
try newDir.create()
To create a directory with specific permissions, specify the perms
parameter:
let newDir = Dir("/path/to/directory/newDirectory")
try newDir.create(perms: [.rwxUser, .rxGroup, .rxOther])
The method throws PerfectError.FileError
if an error creating the directory was encountered.
Deleting a directory from the file system:
let newDir = Dir("/path/to/directory/newDirectory")
try newDir.delete()
The method throws PerfectError.FileError
if an error deleting the directory was encountered.
Use setAsWorkingDir
to set the current working directory to the location of the object's path.
let thisDir = Dir("/path/to/directory/")
try thisDir.setAsWorkingDir()
Returns a new object containing the current working directory.
let workingDir = Dir.workingDir
forEachEntry
enumerates the contents of the directory, passing the name of each contained element to the provided callback.
try thisDir.forEachEntry(closure: {
n in
print(n)
})