B
B
BigKompot2016-07-09 02:55:18
gulp.js
BigKompot, 2016-07-09 02:55:18

Why does gulp-watch work every other time?

I can't understand the strange behavior of gulp-watch. At startup it may work correctly, then it stops responding.
The watcher has gulp-imagemin and an event handler that should remove files from the /build folder when they are removed from the sources.
Can you please tell me where to look for the error?

var watch = require('gulp-watch');
var imagemin = require('gulp-imagemin');
var del = require('del');
var pngquant = require('gulp-pngquant');
var path = require('path');

var imgSrc = 'src/img/*.*';
var imgDst = 'build/img';

gulp.task('del', function() {
    console.log('---------- Удаляю build/');
    return del('build');
});

gulp.task('img', function() {
  return gulp.src(imgSrc)
    .pipe(debug({title: 'src'}))
    .pipe(imagemin())
    .pipe(debug({title: 'imagemin'}))
    .pipe(gulp.dest(imgDst))
    .pipe(debug({title: 'dest'}));
});

gulp.task('watch', function () {
    var watcher = gulp.watch(imgSrc, ['img']);

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BigKompot, 2016-07-09
@BigKompot

The problem was that it was destFilePathreferring to a non-existent file.
As it turned out, path.relative()it does not understand type constructions /**/*.*.
Here is a working version

if (event.type === 'deleted') {
    var filePathFromSrc = path.relative(path.resolve('src/img'), event.path);
    var destFilePath = path.resolve(imgDst, filePathFromSrc);
    del.sync(destFilePath);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question