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

9
我正在尝试让以下代码运行:
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);

根据node.js的文档,由于将objectMode选项设置为true,从此类流中读取非字符串/非缓冲区对象不应该存在问题。但是,我遇到了以下错误:
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)

如果把 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

所以objectMode确实改变了一些东西,但并不完全符合我的预期。

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

1个回答

6

堆栈跟踪表明问题不在Readable流中,而是在您正在将其引导到的Writable流(process.stdout)中。

用一个将objectMode设为trueWritable流替换它,您的错误将会消失。

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}));

2
如果我使用转换流并使用objectMode,它仍然会给我原始的错误。 - Alexander Mills

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接