是ENSOENT从fs.createReadStream不可捕捉?
我无法捕捉到fs.createReadStream()的ENOENT。 这是一个asynchronous函数,它抛出exception在不同的闭包链?
$ 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'
我期待“被抓”被打印而不是错误的堆栈!
fs.createReadStream
与事件发射器风格是asynchronous的,不会抛出exception(这只对同步代码有意义)。 相反,它会发出一个错误事件。
var fs = require('fs') var stream = fs.createReadStream('foo'); stream.on('error', function (error) {console.log("Caught", error);}); stream.on('readable', function () {stream.read();});