Jan 22nd 2014Prevent gulp.js from crashing on error
gulp.js is a new task runner / build system that seems to do many things better than others. I started playing around with it for a new experiment that uses browserify as a module loader.
Old gulpfile
var gulp = require('gulp');
var browserify = require('gulp-browserify');
gulp.task('scripts', function() {
return gulp
.src('js/main.js')
.pipe(browserify({ debug: true }))
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['scripts'], function() {
gulp.watch('js/**/*.js', ['scripts']);
});
Now this worked really well, but whenever I had any errors in my Javascript-files that were supposed to be processed by browserify, the whole process crashed and stopped the watcher.
You can prevent gulp.js and the watcher-script from stopping when errors occur, by handling these errors. To do this, simply add an error listener to where your errors might be thrown.
gulp
.src('...')
.pipe(functionThatMightThrowAnError())
.on('error', onError);
function onError(err) {
console.log(err);
this.emit('end');
}
Emitting the end event inside your error handler is key. The resulting gulpfile, that prevents gulp from crashing when errors are thrown, looks like this:
New gulpfile.js
var gulp = require('gulp');
var browserify = require('gulp-browserify');
gulp.task('scripts', function() {
return gulp
.src('js/main.js')
.pipe(browserify({ debug: true }))
.on('error', onError)
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['scripts'], function() {
gulp.watch('js/**/*.js', ['scripts']);
});
function onError(err) {
console.log(err);
this.emit('end');
}