Node.js“内置”stream可以发出多个错误?
如果我得到一个stream.Readable
或stream.Writable
,例如在调用http.IncomingMessage
, fs.ReadStream
或fs.WriteStream
,我应该假设所有事件可能会多次触发,除非文档另有说明?
我对这些问题的答案特别感兴趣:
-
error
事件可以多次触发吗? - 如果发生
error
事件,还会发生什么其他事件? (如data
?)
这些问题假定:
-
error
事件被捕获并且不会抛出。 - 没有使用第三方库。
代码示例
var options = { method: 'GET', host: 'localhost', path: '/', }; require('http').get(options, function(response) { // ... response.on('end', callback); response.on('error', callback); // ... }); function callback() { // Can this function be called multiple times? }
var s = require('fs').createReadStream('/path/to/file'); s.on('end', callback); s.on('error', callback); function callback() { // Can this function be called multiple times? }
var s = require('fs').createWriteStream('/path/to/file'); s.on('finish', callback); s.on('error', callback); function callback() { // Can this function be called multiple times? }
简短的回答:是的。
长答案:Yyeyeeesss。
只是在开玩笑…正如文档所述, The stream is not closed when the 'error' event is emitted
,所以是的,因为stream在接收到错误后实际打开,所有其他事情仍然可能发生。 所以在收到错误之后,你仍然会收到finish
或end
或者它可能抛出的whatever
事件。
通常end
事件是在错误之后调用的,因为通常错误是关于不能读取/写入更多的数据等,但是不要认为这是一个规则,因为你的程序需要为每种情况做好准备。
如果你希望你的程序在错误100%的时候停止读/写,你必须调用.end()
来确保结束。