Code Monkey home page Code Monkey logo

file-system-watcher's Introduction

Watch changes in the file system using PHP

Latest Version on Packagist Tests GitHub Code Style Action Status Total Downloads

This package allows you to react to all kinds of changes in the file system.

Here's how you can run code when a new file gets added.

use Spatie\Watcher\Watch;

Watch::path($directory)
    ->onFileCreated(function (string $newFilePath) {
        // do something...
    })
    ->start();

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/file-system-watcher

In your project, you should have the JavaScript package chokidar installed. You can install it via npm

npm install chokidar

or Yarn

yarn add chokidar

Usage

Here's how you can start watching a directory and get notified of any changes.

use Spatie\Watcher\Watch;

Watch::path($directory)
    ->onAnyChange(function (string $type, string $path) {
        if ($type === Watch::EVENT_TYPE_FILE_CREATED) {
            echo "file {$path} was created";
        }
    })
    ->start();

You can pass as many directories as you like to path.

To start watching, call the start method. Note that the start method will never end. Any code after that will not be executed.

To make sure that the watcher keeps watching in production, monitor the script or command that starts it with something like Supervisord. See Supervisord example configuration below.

Detected the type of change

The $type parameter of the closure you pass to onAnyChange can contain one of these values:

  • Watcher::EVENT_TYPE_FILE_CREATED: a file was created
  • Watcher::EVENT_TYPE_FILE_UPDATED: a file was updated
  • Watcher::EVENT_TYPE_FILE_DELETED: a file was deleted
  • Watcher::EVENT_TYPE_DIRECTORY_CREATED: a directory was created
  • Watcher::EVENT_TYPE_DIRECTORY_DELETED: a directory was deleted

Listening for specific events

To handle file systems events of a certain type, you can make use of dedicated functions. Here's how you would listen for file creations only.

use Spatie\Watcher\Watch;

Watch::path($directory)
    ->onFileCreated(function (string $newFilePath) {
        // do something...
    });

These are the related available methods:

  • onFileCreated(): accepts a closure that will get passed the new file path
  • onFileUpdated(): accepts a closure that will get passed the updated file path
  • onFileDeleted(): accepts a closure that will get passed the deleted file path
  • onDirectoryCreated(): accepts a closure that will get passed the created directory path
  • onDirectoryDeleted(): accepts a closure that will get passed the deleted directory path

Watching multiple paths

You can pass multiple paths to the paths method.

use Spatie\Watcher\Watch;

Watch::paths($directory, $anotherDirectory);

Performing multiple tasks

You can call onAnyChange, 'onFileCreated', ... multiple times. All given closures will be performed

use Spatie\Watcher\Watch;

Watch::path($directory)
    ->onFileCreated(function (string $newFilePath) {
        // do something on file creation...
    })
    ->onFileCreated(function (string $newFilePath) {
        // do something else on file creation...
    })
    ->onAnyChange(function (string $type, string $path) {
        // do something...
    })
    ->onAnyChange(function (string $type, string $path) {
        // do something else...
    })
    // ...

Stopping the watcher gracefully

By default, the watcher will continue indefinitely when started. To gracefully stop the watcher, you can call shouldContinue and pass it a closure. If the closure returns a falsy value, the watcher will stop. The given closure will be executed every 0.5 second.

use Spatie\Watcher\Watch;

Watch::path($directory)
    ->shouldContinue(function () {
        // return true or false
    })
    // ...

Change the speed of watcher

By default, the changes are tracked every 0.5 seconds, however you could change that.

use Spatie\Watcher\Watch;

Watch::path($directory)
    ->setIntervalTime(1000000) //unit is microsecond therefore -> 0.1s
    // ...rest of your methods

Notice : there is no file watching based on polling going on.

Testing

composer test

Supervisord example configuration

Create a new Supervisord configuration to monitor a Laravel artisan command which calls the watcher. While using Supervisord, you must specicfy your Node.js and PHP executables in your command paramater: env PATH="/usr/local/bin" for Node.js, the absolute path to PHP and your project's path.

[program:watch]
process_name=%(program_name)s
directory=/your/project
command=env PATH="/usr/local/bin" /absolute/path/to/php /your/project/artisan watch-for-files
autostart=true
autorestart=false
user=username
redirect_stderr=true
stdout_logfile=/your/project/storage/logs/watch.log
stopwaitsecs=3600

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

Parts of this package are inspired by Laravel Octane

License

The MIT License (MIT). Please see License File for more information.

file-system-watcher's People

Contributors

adrianmrn avatar alexmanase avatar angeljqv avatar freekmurze avatar joeworkman avatar richardfrankza avatar ryatkins avatar stevemoretz avatar thecaliskan avatar wyattcast44 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

file-system-watcher's Issues

Parsing error in actOnOutput

Good day!

An error was found while reading the file.

Client part of the code:

        Watch::path($watcherDirectory)
            ->onAnyChange(function (string $type, string $path) {
                if ($type === Watch::EVENT_TYPE_FILE_CREATED) {
                    if ($this->validationExtension($path)) {
                        $image = Image::create([
                            'original_path' => $path,
                            'status' => 'queue'
                        ]);
                        sleep(1);
                        event(new ScannerEvent($image));
                    }

                    env('WATCHER_DEBUG', false) ? $this->info('File path: ' . $path) : false;
                }
            })
            ->start();

Error: production.ERROR: Undefined array key 1 {"exception":"[object] (ErrorException(code: 0): Undefined array key 1 at vendor/spatie/file-system-watcher/src/Watch.php:169

protected function actOnOutput(string $output): void
    {
        $lines = explode(PHP_EOL, $output);

        $lines = array_filter($lines);

        foreach ($lines as $line) {
            [$type, $path] = explode(' - ', $line, 2); // In this piece of code

            $path = trim($path);

            match ($type) {
                static::EVENT_TYPE_FILE_CREATED => $this->callAll($this->onFileCreated, $path),
                static::EVENT_TYPE_FILE_UPDATED => $this->callAll($this->onFileUpdated, $path),
                static::EVENT_TYPE_FILE_DELETED => $this->callAll($this->onFileDeleted, $path),
                static::EVENT_TYPE_DIRECTORY_CREATED => $this->callAll($this->onDirectoryCreated, $path),
                static::EVENT_TYPE_DIRECTORY_DELETED => $this->callAll($this->onDirectoryDeleted, $path),
            };

            foreach ($this->onAny as $onAnyCallable) {
                $onAnyCallable($type, $path);
            }
        }
    }

"php": "^8.0.2"
"laravel/framework": "^9.19"

Thanks!

How to start the supervisor?

Discussed in #3

Originally posted by albertopinilla January 11, 2022
Create a command in Laravel and it works without problems, the inconvenience occurs when I want to use the supervisor in Centos 7 and it generates the following error.

This error occurs when I want to start the supervisor
Screenshot 2022-01-11 205955

In the log it shows this error
Screenshot 2022-01-11 210117

Supervisor settings
Screenshot 2022-01-11 210257
.

Could not get to work at all

I could not get this lib to work at all.

$watcher = \Spatie\Watcher\Watch::path($directory);
$watcher->onAnyChange(function (string $type, string $path) {
    echo "{$path} was changed";
})->start();

I used the above code and could never get any kind of change or new file to trigger the callback.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.