Skip to content

Working with Files

The fs library lets you work with files and directories in Lune. You can read, write, copy, and move files around with no extra boilerplate.

Let’s use this directory and file structure for our examples:

  • files.luau
  • dirs.luau
  • hello-world.json
  • Directoryfiles
    • coolstuff.toml
    • super.secret.txt
Show file contents
{
"Hello": "World"
}

Reading and writing files using the fs library is simple and only works with strings:

files.luau
local fs = require("@lune/fs")
-- Print out the contents of all of the files
print(fs.readFile("hello-world.json"))
print(fs.readFile("files/coolstuff.toml"))
print(fs.readFile("files/super.secret.txt"))
-- Create a new file in our "files" directory
fs.writeFile("files/My Favorite Numbers.txt", "2 4 6 8 0")
-- Write to one of our files, overwriting any previous contents
fs.writeFile("files/super.secret.txt", "Super secret message")
-- Remove the new file we created in our "files" directory
fs.removeFile("files/My Favorite Numbers.txt")

Note that the filesystem library works with raw strings for file contents and doesn’t differentiate between binary, UTF-8, or other encodings. It’s up to you to know how your files are structured and handle them appropriately.

Reading and creating directories has a similar API, but with slightly different parameters and return values:

dirs.luau
local fs = require("@lune/fs")
-- Print out the entries found in our directory
-- The "." here means the current directory
print("Contents of current directory:")
for _, entry in fs.readDir(".") do
if fs.isDir(entry) then
print(`📁 {entry}`)
elseif fs.isFile(entry) then
print(`📄 {entry}`)
end
end
-- Create a new directory next to the above entries
fs.writeDir("myCoolDir")
-- Create a new directory in our "files" directory
fs.writeDir("files/myCoolSecondDir")
-- Remove the entire files directory
fs.removeDir("files")

In the above example:

  • fs.readDir returns a table (array) of strings with file and directory names
  • fs.writeDir takes only the directory name (path) to create a directory
  • fs.removeDir removes the directory and everything inside it - use with caution!

This is what our directory structure would look like after running the above examples:

  • files.luau
  • dirs.luau
  • hello-world.json
  • DirectorymyCoolDir/

Now that you know how to work with files and directories, let’s learn about organizing your code with Modules.