is ENOENT from fs.createReadStream uncatchable?


I'm not able to catch ENOENT of fs.createReadStream(). Is this an asynchronous function , which throws exception in a different closure-chain ?

$ node -v
$ cat a.js
fs = require('fs')

try  {
  x = fs.createReadStream('foo');
} catch (e) {
  console.log("Caught" );

$ node a.js

        throw er; // Unhandled 'error' event
Error: ENOENT, open 'foo'

I am expecting 'Caught' to be printed rather than error stack !

Problem courtesy of: Vardhan Varma


fs.createReadStream is asynchronous with the event emitter style and does not throw exceptions (which only make sense for synchronous code). Instead it will emit an error event.

var fs = require('fs')

var stream = fs.createReadStream('foo');
stream.on('error', function (error) {console.log("Caught", error);});
stream.on('readable', function () {;});
Solution courtesy of: Peter Lyons


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.