Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is ENOENT from fs.createReadStream uncatchable?

Tags:

node.js

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 !

like image 656
vrdhn Avatar asked Jun 16 '13 18:06

vrdhn


People also ask

What is FS createReadStream?

The function fs. createReadStream() allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams.

Is createReadStream synchronous?

createReadStream() appears to have a synchronous interface. It does not return a promise or accept a callback to communicate back when it's done or to send back some results. So, it appears synchronous from the interface.


1 Answers

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();}); 
like image 133
Peter Lyons Avatar answered Oct 03 '22 23:10

Peter Lyons