How I can listen folder changes?(watch folder)

Hello, for example I need to move file to other folder if it falls into some watched folder, how I can do it?
I find some script, but it didn’t work well, maybe any idea?
Finded script:

defmodule Daemon do
  use GenServer

  def start_link(opts \\ %{}) do
    GenServer.start_link(__MODULE__, opts, [])
  end

  def init(args) do
    # TODO pass dirs as config
    IO.puts "\n\t\tSTART DAEMON\n"
    {:ok, watcher_pid} = FileSystem.start_link(dirs: ["/home/vagrant/datarama/datarama-import/public/uploads/daemon_store"])
    FileSystem.subscribe(watcher_pid)
    {:ok, %{watcher_pid: watcher_pid}}
  end

  def handle_info({:file_event, watcher_pid, {path, events}}, state) do
    IO.inspect(events)
    IO.inspect(path)
    case List.last(events) do
      :removed ->
        IO.puts "REMOVED"
      :created ->
        IO.puts "CREATED"
        IO.inspect(path)
      :modified ->
        IO.puts "MODIFIED"
      _ ->
        IO.puts "NONE"
    end

    {:noreply, state}
  end

  def handle_info({:file_event, watcher_pid, :stop}, state) do
    {:noreply, state}
  end
end

It seems from your code example you may already be using it, but check https://hex.pm/packages/file_system - it has worked well for me. If you have specific problems with it, can you specify them in more detail?

1 Like