The fs
module provides access to the file system.
Open a file. flags
can have the following values:
r
: readingw
: writing, truncate it if it exists, otherwise create ita
: appending if it exists, otherwise create itr+
: reading and writingw+
: reading and writing, truncate it if it exists, otherwise create ita+
: reading and appending if it exists, otherwise create it
mode
sets access permissions on the file if it is created. It can be a
number or an octal string. '700' means a file is only accessible by you. '777'
means it is accessible by anyone.
Returns a file object.
local file = fs.open('/path/to/file.txt', 'w', '755')
file:write('hello world')
file:close()
Delete a file.
Create a directory. See fs.open
for documentation on mode
.
Delete a directory. It must be empty.
Change the permissions of a file/directory. See fs.open
for documentation on
mode
.
Change the owner of a file/directory. uid
and gid
should be numbers.
Retrieve information about a file/directory. Returns a table with the following keys:
uid
: User who owns the file.gid
: Group that owns the file.size
: File size in bytes.mode
: Access permissions. Seefs.open
.is_dir
:true
if it is a directory.is_fifo
:true
if it is a [FIFO].atime
: Time the file was last accessed (second precision).atimensec
: Time the file was last accessed (nanosecond precision).mtime
: Time the file was last accessed (second precision).mtimensec
: Time the file was last accessed (nanosecond precision).ctime
: Time the file was last changed (second precision).ctimensec
: Time the file was last changed (nanosecond precision).birthtime
: Time the file was created (second precision).birthtimensec
: Time the file was created (nanosecond precision).
Same as fs.stat
, but doesn't follow symlinks.
Rename a file.
Create a hard link.
Create a symlink.
Read the value of a symlink.
Get the full contents of a file as a string.
Write a string to a file. Truncates the file if it already exists.
Get a temporary filename.
Get the current working directory.
Change the current working directory.
Get a list of files/subdirectories in a directory.
Get a list of all files under a directory and its descendent subdirectories. Returns a flat list of filenames.
fs.with_tempdir(function(dir)
fs.chdir(dir)
fs.writefile('a', '')
fs.writefile('b', '')
fs.mkdir('c')
fs.writefile('c/d', '')
local filenames = fs.readdir_r('.')
# filenames == { 'a', 'b', 'c/d' }
end)
Delete a file or directory. If it is a directory, its contents are deleted as well. Be careful with this one!
Extract the directory, basename, and extension from a filename, respectively.
assert(fs.dirname ('/path/to/file.txt') == '/path/to/')
assert(fs.basename('/path/to/file.txt') == 'file')
assert(fs.extname ('/path/to/file.txt') == '.txt')
Create a directory, pass it to a callback, and delete the directory when the callback returns.
fs.with_tempdir(function(dir)
# dir will be something like '/tmp/lua_bVjBeR'
end)