Search code examples
gruntjsdelete-filegrunt-contrib-watch

Watching for deleted files with grunt


Using grunt-watch to monitor for changes to files is great for add/change operations, because when it invokes the task with the change list the task's files (or fileSrc) property will contain the added/changed files.

Not so with deleted files. If you watch for deleted files, and invoke a task, the deleted file will not appear in the task's filesSrc property or the normalized portion of the files property.

Aside from manually normalizing the orig property of a particular files element, is there a way to force the deleted file to appear in fileSrc or the normalized part of files? If not, what's the best way to normalize orig (I don't want to reinvent the wheel)?


Solution

  • It's likely the plugin is dumping the deleted files from the files array by design, the plugin however does emit a watch event that you can listen for:

    grunt.initConfig({
      watch: {
        scripts: {
          files: ['**'],
        },
      },
    });
    grunt.event.on('watch', function(action, filepath, target) {
      if (target === 'scripts' && action === 'deleted') {
        // your code goes here
      }
    });
    

    There's also ways to set up a watch task specific that runs a specific task for when the watcher detects a deletion. Both methods are listed in the plugin's documentation.