Skip to content

DirectoryWatcher

The DirectoryWatcher library provides functionality to monitor changes in a specified directory and its subdirectories. It allows you to set up callbacks for various file system events.

Creating a DirectoryWatcher

DirectoryWatcher.new(path, recursive)

Creates a new DirectoryWatcher object.

  • path: A string representing the path to watch, relative to the Workspace folder (you could pass an empty string for the root Workspace folder).
  • recursive: A boolean indicating whether to watch subdirectories recursively.
local watcher = DirectoryWatcher.new("MyFolder", true)

DirectoryWatcher Methods

watcher:start()

Starts watching the specified directory.

watcher:start()

watcher:stop()

Stops watching the directory.

watcher:stop()

watcher:OnChanged(callback)

Sets a callback function to be called when a file is modified.

watcher:OnChanged(function(path)
    print("File changed:", path)
end)

watcher:OnCreated(callback)

Sets a callback function to be called when a new file is created.

watcher:OnCreated(function(path)
    print("File created:", path)
end)

watcher:OnDeleted(callback)

Sets a callback function to be called when a file is deleted.

watcher:OnDeleted(function(path)
    print("File deleted:", path)
end)

watcher:OnRenamed(callback)

Sets a callback function to be called when a file is renamed.

watcher:OnRenamed(function(path)
    print("File renamed:", path)
end)

watcher:OnOverflow(callback)

Sets a callback function to be called when the watcher buffer overflows.

watcher:OnOverflow(function()
    print("Watcher buffer overflow occurred")
end)

watcher:GetPath()

Returns the path being watched, relative to the Workspace folder.

local path = watcher:GetPath()
print("Watching path:", path)

watcher:IsRecursive()

Returns a boolean indicating whether the watcher is set to watch subdirectories recursively.

local isRecursive = watcher:IsRecursive()
print("Is watching recursively:", isRecursive)

Example Usage

local watcher = DirectoryWatcher.new("MyFolder", true)

watcher:OnChanged(function(path)
    print("File changed:", path)
end)

watcher:OnCreated(function(path)
    print("File created:", path)
end)

watcher:OnDeleted(function(path)
    print("File deleted:", path)
end)

watcher:OnRenamed(function(path)
    print("File renamed:", path)
end)

watcher:start()

-- Do some work or wait for events

watcher:stop()