F
F
faragly2015-10-16 09:59:55
gulp.js
faragly, 2015-10-16 09:59:55

How to pause watching files for the duration of a function in GulpJS?

Welcome all! I use gulp-watch to beauitify js files on the fly. A situation arose - beautify changes the file, the watcher works again and it turns out a vicious circle ... Before starting the function, you need to unwatch and after the end, return the wiretap to the file again.

var w = watch('./source/js/**/*.js', {verbose: true});
    w.on('data', function (vinyl) {
        console.log(vinyl.relative);
        w.unwatch(vinyl.relative);
    });

This code, in theory, should show the changed file once and stop listening, and on the second change, do not show anything anymore, but apparently I'm doing something wrong.
gulp.task('watch:js', function () {
    var w = watch('./source/{amcharts,js}/**/*.js', {verbose: true});
    w.on('data', function (vinyl) {
        console.log(vinyl.relative);
        // Beautify JS file
        var jsBeautifier = (function (file) {
            var q = Q.defer();
            w.unwatch(file);
            gulp.src(file)
                .pipe(prettify({
                    config: './.jsbeautifyrc'
                }))
                .pipe(gulp.dest(function(file) {
                    return file.base;
                }))
                .on('end', function () {
                    w.add(file);
                    q.resolve(file);
                });
            return q.promise;
        }).call(this);
    });
});

Help to use the plugin correctly.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
faragly, 2015-10-17
@faragly

Problem solved. To stop listening, you need to use the absolute path to the file, not the relative one, that is

var w = watch('./source/js/**/*.js', {verbose: true, events: ['change']});
    w.on('data', function (vinyl) {
        w.unwatch(vinyl.path);
        // тут операция и в on end добавляем прослушку обратно
    });

But when editing, the file will be processed several times, since the event will be called first change, and then addto prevent this from happening, I left the event only events: ['change']in the watch parameters

C
ChickenGrinder, 2015-10-17
@ChickenGrinder

This is a misuse of watch and beatify in my opinion.
beatify - should not work on changing the file, it should be a separate task.
Even if you make the watch task work correctly, then this is violence against yourself. I submit, edit the file in the editor, and after each save, I get a warning that the file has changed from outside ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question