从可读流中读取对象会导致 TypeError 异常 [英] Reading objects from readable stream causes TypeError exception

查看:17
本文介绍了从可读流中读取对象会导致 TypeError 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make the following code work:

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 的 Streams 文档,阅读非-由于 objectMode 选项设置为 true,来自此类流的字符串/非 Buffer 对象.然而我最终得到的是以下错误:

According to Streams documentation of node.js there should be no problem reading non-string/non-Buffer objects from such stream thanks to objectMode option being set to true. And yet what I end up with is the following error:

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".

If this.push({a: 1}) was changed to, let's say this.push('abc') then everything works like a charm and my console window gets flooded with 'abc'.

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

On the other hand, if I set objectMode to false and still try to push objects like {a: 1} then the error message changes to:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string, Buffer, or Uint8Array

所以 objectMode 确实改变了一些东西,但并不完全像我期望的那样.

So objectMode does change some things but not exactly as I would expect it to.

我使用的是 9.4.0 版本的 node.js.

I'm using 9.4.0 version of node.js.

推荐答案

stacktrace 表明问题不在 Readable 流中,而是在 Writable 流中你正在将它传送到 (process.stdout).

The stacktrace indicates that the problem is not in the Readable stream, but in the Writable stream that you're piping it to (process.stdout).

objectMode 设置为 trueWritable 流替换它,你的错误就会消失.

Replace it with a Writable stream that has objectMode set to true, and your error will go away.

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

这篇关于从可读流中读取对象会导致 TypeError 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆