写入时出错


¥Errors while writing

在处理 writable._write()writable._writev()writable._final() 方法期间发生的错误必须通过调用回调并将错误作为第一个参数传递来传播。从这些方法中抛出 Error 或手动触发 'error' 事件会导致未定义的行为。

¥Errors occurring during the processing of the writable._write(), writable._writev() and writable._final() methods must be propagated by invoking the callback and passing the error as the first argument. Throwing an Error from within these methods or manually emitting an 'error' event results in undefined behavior.

如果 Readable 流在 Writable 触发错误时通过管道传输到 Writable 流,则 Readable 流将被取消传输。

¥If a Readable stream pipes into a Writable stream when Writable emits an error, the Readable stream will be unpiped.

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

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    if (chunk.toString().indexOf('a') >= 0) {
      callback(new Error('chunk is invalid'));
    } else {
      callback();
    }
  },
});