Search code examples
node.jsbuildgulp

Run code after gulp task done with all files


So I have been trying out Gulp to see how it compares to Grunt as far as speed and I am pretty impressed with the results but I have one thing I don't know how to do in Gulp.

So I have this gulp task to minify HTML:

gulp.task('html-minify', function() {
  var files = [
    relativePaths.webPath + '/*.html',
    relativePaths.webPath + '/components/**/*.html',
    relativePaths.webPath + '/' + relativePaths.appPath + '/components/**/*.html'
  ];

  var changedFiles = buildMetaData.getChangedFiles(files);

  //TODO: needs to execute only after successful run of the task
  buildMetaData.addBuildMetaDataFiles(changedFiles);
  buildMetaData.writeFile();
  return gulp.src(changedFiles, {
      base: relativePaths.webPath
    })
    .pipe(filelog())
    .pipe(minifyHtml({
      empty: true,
      quotes: true,
      conditionals: true,
      comments: true
    }))
    .pipe(gulp.dest(relativePaths.webPath + '/' + relativePaths.appPath +  '/' + relativePaths.buildPath));
});

The buildMetaData object has custom functionality that I need and why I can't use plugins like gulp-changed. What I am trying to figure out is how (if possible) to run a block of code after the minify is done process all files and it run successfully. Is something like this possible with gulp?


Solution

  • You could just make a task which depends on html-minify:

    gulp.task('other-task', ['html-minify'], function() {
      //stuff
    });
    

    You could also listen for the stream end event inside the html-minify task:

    gulp.task('html-minify', function(done) {
      var files = [
        relativePaths.webPath + '/*.html',
        relativePaths.webPath + '/components/**/*.html',
        relativePaths.webPath + '/' + relativePaths.appPath + '/components/**/*.html'
      ];
    
      var changedFiles = buildMetaData.getChangedFiles(files);
    
      //TODO: needs to execute only after successful run of the task
      buildMetaData.addBuildMetaDataFiles(changedFiles);
      buildMetaData.writeFile();
      var stream = gulp.src(changedFiles, {
          base: relativePaths.webPath
        })
        .pipe(filelog())
        .pipe(minifyHtml({
          empty: true,
          quotes: true,
          conditionals: true,
          comments: true
        }))
        .pipe(gulp.dest(relativePaths.webPath + '/' + relativePaths.appPath +  '/' + relativePaths.buildPath));
    
      stream.on('end', function() {
        //run some code here
        done();
      });
      stream.on('error', function(err) {
        done(err);
      });
    });