46

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
v0.10.9
$ cat a.js
fs = require('fs')

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

$ node a.js

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ENOENT, open 'foo'

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

vrdhn
  • 4,024
  • 3
  • 31
  • 39

1 Answers1

57

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.

const fs = require('fs')

const stream = fs.createReadStream('foo');
stream.on('error', function (error) {console.log("Caught", error);});
stream.on('ready', function () {stream.read();});
Márius Rak
  • 1,356
  • 2
  • 15
  • 35
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • 3
    I guess you're saying the stream object is returned synchronously, but the opening of its file happens asynchronously with event emission. Is there no chance the error event will be emitted before `stream.on('error', ...)` takes effect? That's what I see if I type this into node's REPL a line at a time. – Jeffrey Scofield Apr 22 '14 at 20:52
  • 4
    Yes, you can be assured that the current tick will complete before any events fire. So as long as you bind your handlers right away, all is well. – Peter Lyons Apr 22 '14 at 21:11
  • Hmm that's really confusing behaviour! – UpTheCreek Feb 04 '16 at 13:23
  • Thanks for this. Very helpful. Why don't I see this in the docs anywhere? (I'm assuming I'm misreading the docs in some fundamental fashion) – verveguy Aug 29 '16 at 13:44
  • The docs describe the `error` event from ReadableStream [here](https://nodejs.org/docs/latest/api/all.html#stream_event_error_1). You might have a hard time finding it because you have to start at the `createReadStream` docs and click the link to navigate to `ReadableStream` to find details on the events emitted. – Peter Lyons Aug 29 '16 at 17:17