综合编程

is ENOENT from fs.createReadStream uncatchable?

微信扫一扫,分享到朋友圈

is ENOENT from fs.createReadStream uncatchable?
0

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 !

Problem courtesy of: Vardhan Varma

Solution

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 () {stream.read();});

Solution courtesy of: Peter Lyons

阅读原文...


Node.js Recipes

Django之无名分组,有名分组

上一篇

ACM launches investigation into abuse of dominance by Apple in its App Store

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
is ENOENT from fs.createReadStream uncatchable?

长按储存图像,分享给朋友