writable.destroy([error])


  • error <Error> 可选,通过 'error' 事件发出的错误。
  • 返回:<this>

销毁流。可以选择触发一个 'error' 事件,并触发一个 'close' 事件(除非 emitClose 设置为 false)。调用此方法后,可写流将结束,随后对 write()end() 的调用将导致 ERR_STREAM_DESTROYED 错误。 这种方式会立即且破坏性地销毁流。先前对 write() 的调用可能尚未完成,并可能触发 ERR_STREAM_DESTROYED 错误。如果数据应在关闭前刷新,应使用 end() 而不是 destroy,或者在销毁流之前等待 'drain' 事件。

【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().】