Search code examples
javascriptnode.jsgulpgulp-sass

How can I set up a watcher to copy files to other files inside same folders?


Here's what I have so far and what I have tried:

In my application I have files with a structure like this

/app/learn/content/ab.html
/app/learn/content/bc.html
/app/learn/content/base.html
/app/write/content/ab.html
/app/write/content/bc.html
/app/write/content/base.html
/app/xx/ab.html
/app/xx/bc.html
/app/xx/base.html

I set up a watcher like this:

var abc = {
    src: [
        '**/ab.html',
        '**/bc.html',
    ],
}
gulp.task('watchHTMLs', function () {
    gulp.watch(abc.src, function (file) {
        return gulp.src(path.basename(file.path))
          .pipe(rename('base.html'))
          .pipe(gulp.dest('./'));
    })
});

What I would like to do is to watch for files with ab.html or bc.html file names and then copy these to base.html in the same directory when one changes. But so far my watcher starts but then nothing at all happens when I change one of the ab.html or bc.html files. The watcher does not even seem to fire.

Can anyone point me to what I am doing wrong?


Solution

  • Using an unscoped globstar ** over your entire project is a bad idea. **/ab.html matches ab.html in all folders of your project including node_modules. Depending on how many nested folders there are in node_modules this can take a looong time to finish. If it ever does.

    Also the file you receive from gulp.watch() only has an absolute path, so you need to feed the base option with the current working directory to gulp.src().

    Finally you only want to change the name of your file, not the entire path. Use the basename option of gulp-rename.

    All this adds up to:

    var abc = {
      src: [
        'app/**/ab.html',
        'app/**/bc.html'
      ],
    };
    gulp.task('watchHTMLs', function () {
      gulp.watch(abc.src, function (file) {
        return gulp.src(file.path, { base: process.cwd() })
          .pipe(rename({basename:'base'}))
          .pipe(gulp.dest('./'));
      });
    });