Skip to content

Instantly share code, notes, and snippets.

@rudijs
Last active December 1, 2023 08:20
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save rudijs/9148283 to your computer and use it in GitHub Desktop.
Save rudijs/9148283 to your computer and use it in GitHub Desktop.
GulpJS Jshint with Notify on Error
var gulp = require('gulp'),
watch = require('gulp-watch'),
// This will keeps pipes working after error event
plumber = require('gulp-plumber'),
// linting
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
// Used in linting custom reporter
map = require('map-stream'),
events = require('events'),
notify = require('gulp-notify'),
emmitter = new events.EventEmitter(),
path = require('path');
// Custom linting reporter used for error notify
var jsHintErrorReporter = map(function (file, cb) {
if (!file.jshint.success) {
file.jshint.results.forEach(function (err) {
if (err) {
//console.log(err);
// Error message
var msg = [
path.basename(file.path),
'Line: ' + err.error.line,
'Reason: ' + err.error.reason
];
// Emit this error event
emmitter.emit('error', new Error(msg.join('\n')));
}
});
}
cb(null, file);
});
gulp.task('lint', function () {
gulp.src([
'app/components/**/*.js',
'!app/components/app/translations.js'
])
.pipe(watch())
.pipe(plumber())
.pipe(jshint('.jshintrc', {fail: true}))
.pipe(jshint.reporter(stylish)) // Console output
.pipe(jsHintErrorReporter) // If error pop up a notify alert
.on('error', notify.onError(function (error) {
return error.message;
}));
});
@zeezali
Copy link

zeezali commented Feb 28, 2014

Thanks for sharing this!
I was really struggling trying to figure out how notifications appear on errors.

@motionharvest
Copy link

what role does watch() play?

@bfintal
Copy link

bfintal commented Sep 1, 2015

Modified the error message to include all of the errors in a single emit:

.pipe( map( function ( file, callback ) {
    if ( ! file.jshint.success ) {
        var msg = [];
        file.jshint.results.forEach( function ( err, i ) {
            if ( err ) {
                // Error message
                msg.push(
                    '#' + ( i + 1 ) + '\t' + 'Line: ' + err.error.line + '\t' + path.basename(file.path) + '\n' +
                    err.error.reason
                );

            }
        } );
        emmitter.emit('error', new Error('\n' + msg.join('\n')));
    }
    callback( null, file );
} ) )

@bfintal
Copy link

bfintal commented Sep 1, 2015

Just discovered this built-in jshint notification with only gulp-notify: https://github.com/mikaelbr/gulp-notify#as-jshint-reporter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment