writable.destroy([error])


  • error <Error> 可选,与 'error' 事件一起触发的错误。

    ¥error <Error> Optional, an error to emit with 'error' event.

  • 返回:<this>

    ¥Returns: <this>

销毁流可选地触发 'error' 事件,并且触发 'close' 事件(除非 emitClose 设置为 false)。在此调用之后,则可写流已结束,随后对 write()end() 的调用将导致 ERR_STREAM_DESTROYED 错误。这是销毁流的销毁性和直接的方式。先前对 write() 的调用可能没有排空,并且可能触发 ERR_STREAM_DESTROYED 错误。如果数据应该在关闭之前刷新,或者在销毁流之前等待 'drain' 事件,则使用 end() 而不是销毁。

¥Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the writable stream has ended and subsequent calls to write() or end() will result in an ERR_STREAM_DESTROYED error. This is a destructive and immediate way to destroy a stream. Previous calls to write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. Use end() instead of destroy if data should flush before close, or wait for the 'drain' event before destroying the stream.

const { Writable } = require('node:stream');

const myStream = new Writable();

const fooErr = new Error('foo error');
myStream.destroy(fooErr);
myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error 
const { Writable } = require('node:stream');

const myStream = new Writable();

myStream.destroy();
myStream.on('error', function wontHappen() {}); 
const { Writable } = require('node:stream');

const myStream = new Writable();
myStream.destroy();

myStream.write('foo', (error) => console.error(error.code));
// ERR_STREAM_DESTROYED 

一旦 destroy() 被调用,任何进一步的调用都将是空操作,除了来自 _destroy() 的其他错误可能不会作为 'error' 触发。

¥Once destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'.

实现者不应覆盖此方法,而应实现 writable._destroy()

¥Implementors should not override this method, but instead implement writable._destroy().