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.
Example File Tree
Section titled “Example File Tree”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"}
[you]cool = trueawesome = "yep"
Hey, you're not supposed to be in here!
Reading and writing files using the fs
library is simple and only works with strings:
local fs = require("@lune/fs")
-- Print out the contents of all of the filesprint(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" directoryfs.writeFile("files/My Favorite Numbers.txt", "2 4 6 8 0")
-- Write to one of our files, overwriting any previous contentsfs.writeFile("files/super.secret.txt", "Super secret message")
-- Remove the new file we created in our "files" directoryfs.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.
Directories
Section titled “Directories”Reading and creating directories has a similar API, but with slightly different parameters and return values:
local fs = require("@lune/fs")
-- Print out the entries found in our directory-- The "." here means the current directoryprint("Contents of current directory:")for _, entry in fs.readDir(".") do if fs.isDir(entry) then print(`📁 {entry}`) elseif fs.isFile(entry) then print(`📄 {entry}`) endend
-- Create a new directory next to the above entriesfs.writeDir("myCoolDir")
-- Create a new directory in our "files" directoryfs.writeDir("files/myCoolSecondDir")
-- Remove the entire files directoryfs.removeDir("files")
In the above example:
fs.readDir
returns a table (array) of strings with file and directory namesfs.writeDir
takes only the directory name (path) to create a directoryfs.removeDir
removes the directory and everything inside it - use with caution!
Resulting File Tree
Section titled “Resulting File Tree”This is what our directory structure would look like after running the above examples:
- files.luau
- dirs.luau
- hello-world.json
DirectorymyCoolDir/
- …
What’s Next?
Section titled “What’s Next?”Now that you know how to work with files and directories, let’s learn about organizing your code with Modules.