app.watcher - 文件监听 API
使用 FSEvents 监听文件系统变化。
方法
app.watcher.watch(path, callback)
开始监听目录或文件的变化。
参数:
path(string) - 要监听的路径(目录或文件)callback(function) - 变化回调函数,参数为事件表
回调参数格式:
event.path(string) - 变化的文件路径event.flags(array) - 变化类型数组:"created"- 文件创建"removed"- 文件删除"modified"- 文件修改"renamed"- 文件重命名"metadata"- 元数据变化
返回值: string, error - 监听器 ID
local id, err = app.watcher.watch("/path/to/dir", function(event)
app.log.info("变化: " .. event.path)
app.log.info("类型: " .. table.concat(event.flags, ", "))
end)
app.watcher.stop(id)
停止指定监听器。
参数:
id(string) - 监听器 ID
返回值: boolean, error
app.watcher.stop(id)
app.watcher.stopAll()
停止当前插件的所有监听器。
返回值: boolean
app.watcher.stopAll()
app.watcher.list()
列出当前插件的活跃监听器。
返回值: array<table> - 每项: {id, path}
local watchers = app.watcher.list()
for _, w in ipairs(watchers) do
app.log.info(w.id .. " → " .. w.path)
end
说明
- 每个插件最多 50 个监听器
- 事件延迟约 500ms(FSEvents 合并机制)
- 监听器在插件卸载时自动停止
- 回调在插件执行队列上调用(线程安全)
- 目录监听包含递归子目录变化
示例
监听目录变化
local watchId = nil
function MyPlugin:onLoad()
-- 开始监听下载目录
local downloads = app.path.home() .. "/Downloads"
watchId = app.watcher.watch(downloads, function(event)
for _, flag in ipairs(event.flags) do
if flag == "created" then
app.notification.show("新文件", app.path.basename(event.path))
end
end
end)
end
function MyPlugin:onUnload()
if watchId then
app.watcher.stop(watchId)
end
end
自动处理新文件
function MyPlugin:init()
self:registerHandler("start_watch", self.handleStartWatch)
self:registerHandler("stop_watch", self.handleStopWatch)
end
function MyPlugin:handleStartWatch(context)
local dir = context.currentDirectory
self.watchId = app.watcher.watch(dir, function(event)
for _, flag in ipairs(event.flags) do
if flag == "created" then
local ext = app.path.extension(event.path)
if ext == "png" or ext == "jpg" then
app.log.info("新图片: " .. event.path)
-- 自动处理...
end
end
end
end)
if self.watchId then
app.notification.show("监听", "开始监听: " .. dir)
end
end
function MyPlugin:handleStopWatch(context)
if self.watchId then
app.watcher.stop(self.watchId)
self.watchId = nil
app.notification.show("监听", "已停止监听")
end
end