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
开发者文档
使用帮助
使用说明 脚本菜单 常见问题
脚本开发
开发指南
插件开发
快速开始 开发指南 示例插件
API 参考
概览 API 查询 插件信息 日志 Finder 上下文 插件设置 国际化
UI 与交互
对话框 进度条 系统通知 选择器 WebView 状态栏 Dock
文件与路径
文件操作 路径工具 Finder 操作 废纸篓 扩展属性 元数据 文件监听
数据格式
JSON Plist CSV XML PDF 图片
文本与编码
字符串 正则表达式 日期时间 颜色 加密编码
系统
Shell 命令 进程管理 应用管理 系统信息 AppleScript 快捷指令
系统信息
网络信息 电源/电池 屏幕/外观 音频控制 蓝牙设备 位置服务
网络
HTTP 请求 WebSocket URL 工具
输入与剪贴板
键盘模拟 鼠标模拟 全局热键 剪贴板 窗口管理
存储
SQLite Keychain UserDefaults
媒体
文字识别 二维码
工具
归档 类型标识 分享 定时器 防休眠 并发/协程