Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Reading objects from readable stream causes TypeError exception

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

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)

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

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

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

I'm using 9.4.0 version of node.js.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...