gulpgulp-watchgulp-connect

Error write after end on gulp.watch with gulp-connect


I have a simple watch on gulp that reloads all js files (using gulp-connect) when one of them has changes, but I'm getting the following error whenever the task asociated runs:

[15:14:35] Starting 'livereload:js'...
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
    at ServerResponse.res.inject.res.write (C:\dev\test-livereload\node_modules\connect-livereload\index.js:115:37)
    at ReadStream.ondata (_stream_readable.js:555:20)
    at emitOne (events.js:96:13)
    at ReadStream.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at ReadStream.Readable.push (_stream_readable.js:134:10)
    at onread (fs.js:1984:12)
    at FSReqWrap.wrapper [as oncomplete] (fs.js:681:17)

Here's the code:

gulp.task('livereload:js', function() {
  return gulp.src([paths.APP_ROOT + '/**/*.js'])
    //.pipe(wait(2000))  // if I add a small wait it doesn't crash as often
    .pipe(connect.reload());
});

gulp.task('run-watch', function() {
  gulp.watch([paths.APP_ROOT + '/**/*.js'], ['livereload:js']);
});

I have a similar task that checks for changes in scss files and compiles them before reloading that works fine.


Solution

  • I found a workaround. Instead of gulp.watch I use the gulp-watch package to run connect.reload(), which can be used in a pipe.

    I think there was a race condition that was triggering the reload before the files were ready.