Handling Errors with Streams

Learning Gulp : part 8 of 22 published on Jul 22, 2015

What if the file was named incorrectly? What happens?

Change the string index.html to OMG_WRONG_FILE.html and rerun the script.

// /streams.js
var fs = require("fs");
var stream = fs.createReadStream(__dirname + "/contents/OMG_WRONG_FILE.html");

stream.on("data", function(chunk) {
  // just output chunk to terminal

stream.on("end", function() {

Running the script this time results in:

$ node streams.js
        throw er; // Unhandled 'error' event


If we read the error message carefully, then we can see that there is an error event we can listen to. So lets listen for that event.

// /streams.js
stream.on("error", function(er) {
  console.log("error", er);

Now we rerun the script and see:

$ node streams.js
error { [Error: ENOENT, open '/Users/jonathanbirkholz/js/gulptest/contents/OMG_WRONG_FILE.html']
  errno: -2,
  code: 'ENOENT',
  path: '~/YOUR_DIRECTORY/contents/OMG_WRONG_FILE.html' }

And that is it for now. We will come back and use some of what we learned later.

Next: Validate JavaScript