从可读流中读取对象会导致TypeError异常

twa*_*ski 8 javascript stream node.js

我正在尝试使以下代码起作用:

var stream = require('stream');

class MyReadable extends stream.Readable {
  constructor(options) {
    super(options);
  }
  _read(size) {
    this.push({a: 1});
  }
}

var x = new MyReadable({objectMode: true});
x.pipe(process.stdout);
Run Code Online (Sandbox Code Playgroud)

根据node.js的Streams文档,由于objectMode选项设置为true因此从此类流中读取非字符串/非Buffer对象应该没有问题。但是我最终遇到了以下错误:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer
    at validChunk (_stream_writable.js:253:10)
    at WriteStream.Writable.write (_stream_writable.js:288:21)
    at MyReadable.ondata (_stream_readable.js:646:20)
    at MyReadable.emit (events.js:160:13)
    at MyReadable.Readable.read (_stream_readable.js:482:10)
    at flow (_stream_readable.js:853:34)
    at resume_ (_stream_readable.js:835:3)
    at process._tickCallback (internal/process/next_tick.js:152:19)
    at Function.Module.runMain (module.js:703:11)
    at startup (bootstrap_node.js:193:16)
Run Code Online (Sandbox Code Playgroud)

如果将this.push({a:1})更改为,假设this.push('abc'),那么所有内容都像一个超级按钮,并且我的控制台窗口中充满了'abc'。

另一方面,如果我将objectMode设置为false并且仍然尝试推送诸如{a:1}之类的对象,则错误消息将更改为:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string, Buffer, or Uint8Array
Run Code Online (Sandbox Code Playgroud)

因此,objectMode确实会更改某些内容,但并不完全符合我的预期。

我正在使用9.4.0版本的node.js。

Rob*_*sen 6

stacktrace指示问题不在于Readable流中,而Writable在于您将其用管道传递到(process.stdout)的流中。

将其替换为WritableobjectMode设置为的流,true您的错误就会消失。

var stream = require('stream');

class MyReadable extends stream.Readable {
  constructor(options) {
    super(options);
  }
  _read(size) {
    this.push({a: 1});
  }
}

class MyWritable extends stream.Writable {
  constructor(options) {
    super(options);
  }
  _write(chunk) {
    console.log(chunk);
  }
}

var x = new MyReadable({objectMode: true});
x.pipe(new MyWritable({objectMode: true}));
Run Code Online (Sandbox Code Playgroud)

  • 如果我使用转换流并使用objectMode,仍然会给我原始错误 (2认同)