Gulp – fail run-sequence with a correct exit code

gulp-2x

You may use the run-sequence module in your gulp tasks to make sure a task is finished before launching some others (example: make sure the build folder is cleaned up before launching the build related tasks).

The problem with run-sequence is that you always get a 0 exit code, no matter the task succeeded or failed. So you can’t rely on that in Continuous Integration tools (such as Travis CI).

I bumped into that problem on one of my projects, here’s how I solved it:

var runSequence = require('run-sequence');

gulp.task('build', function (cb) {
  runSequence(
    ['clean'],
    ['compile', 'extras', 'images'],
    // this callback is executed at the end, if any of the previous tasks errored, 
    // the first param contains the error
    function (err) {
      //if any error happened in the previous tasks, exit with a code > 0
      if (err) {
        var exitCode = 2;
        console.log('[ERROR] gulp build task failed', err);
        console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode);
        return process.exit(exitCode);
      }
      else {
        return cb();
      }
    }
  );
});

This bug happens with gulp@3.9.0, in the next major version (v4.0.0), there will be a built-in gulp.series API that should fix this kind of problem.

Leave a Reply

Your email address will not be published. Required fields are marked *