Search code examples
gulpgulp-watch

Gulp: delete generated .png from dest when .svg removed from src


I have a Gulp task creating .png fallbacks for .svg files in a src folder:

gulp.task('svg2png', ['svg'], function() {
  return gulp.src(src + '/svg/**/*.svg')
  .pipe(plugins.newer(dest + '/svg'))
  .pipe(plugins.svg2png())
  .pipe(gulp.dest(dest + '/svg'))
  .pipe(plugins.notify({
    message: 'svg2png task complete', onLast: true
  }));
});

(The svg task is svgmin)

I wanted to tidy up behind myself by deleting generated files (in the dest folder) and thought to extend the watch task as below:

gulp.task('watch', function () {
  var watchSvg = gulp.watch('src/svg/**/*.svg', ['svg2png']);

  watchSvg.on('change', function(event) {
    if (event.type === 'deleted') {
      var filePathFromSrc = path.relative(path.resolve('src'), event.path);
      var destFilePath = path.resolve('dist', filePathFromSrc);
      del.sync(destFilePath);
    }
  });
});

This works in deleting the .svg but what I'd also like to do is delete the matching .png file so there are no orphans. I'm blindly trusting the Handling the Delete Event on Watch recipe so I'm already outside my level of Gulp / JS knowledge to experiment with this modification.

Thanks in advance.


Solution

  • Assuming the .png file is generated into the same folder as the minified .svg file, the following should work:

    watchSvg.on('change', function(event) {
      if (event.type === 'deleted') {
        var filePathFromSrc = path.relative(path.resolve('src'), event.path);
        var destFilePath = path.resolve('dist', filePathFromSrc);
        del.sync(destFilePath);
        var pngDestFilePath = destFilePath.replace(/.svg$/, '.png');
        del.sync(pngDestFilePath);
      }
    });