写入时出错


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

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

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

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

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.

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

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

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