来自fs.createReadStream的ENOENT无法访问?

时间:2013-06-16 18:49:58

标签: node.js

我无法捕捉到fs.createReadStream()的ENOENT。这是一个异步函数,它在不同的闭包链中抛出异常吗?

$ 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'

我期待打印'抓住'而不是错误堆叠!

1 个答案:

答案 0 :(得分:46)

fs.createReadStream与事件发射器样式是异步的,不会抛出异常(只对同步代码有意义)。相反,它会发出错误事件。

var fs = require('fs')

var stream = fs.createReadStream('foo');
stream.on('error', function (error) {console.log("Caught", error);});
stream.on('readable', function () {stream.read();});