写入时出错


【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();
    }
  },
});