Ben Aston
Ben Aston

Reputation: 55729

Why does this stream function result in an error?

I have written a function to be piped into that will log the supplied arguments to the console.

function sconsole() {
    var stream = new Stream.Transform({objectMode: true}),
        foo = [].slice.call(arguments);

    stream._transform = function (data, encoding, callback) {
        console.log.apply(null, foo);
        callback(null, data);
    };

    return stream;
}

Example use:

stream
  .pipe(sconsole('foo'))
  .pipe(...);

But when used in the final position of a sequence of pipe invocations, it causes the following error:

TypeError: Invalid non-string/buffer chunk

Why?

Upvotes: 2

Views: 425

Answers (1)

mscdex
mscdex

Reputation: 106698

You can't mix/pipe objectMode and non-objectMode streams together like that because they work with different data types.

However, if you have node v0.12+ or io.js, you could use something like readableObjectMode: true, which sets the readable side of your transform stream for reading objects, but writing bytes as normal. You can do something similar for the other way around with writableObjectMode: true (objectMode: true is equivalent to setting both of these properties to true). This way you can convert between one stream type to another.

Upvotes: 2

Related Questions