Genuifx
Genuifx

Reputation: 31

Nodejs: can I set objectMode of stream.Transform like this?

can I set objectMode like the following code? if not, how to fix it?

tks, bro.

class com extends stream.Transform {
    constructor(opt) {
        super(Object.assign({}, {objectMode: true}, opt));
    }
    _transform(chunk, enc, callback) {
        let ret = compiler(chunk);
        this.push(ret);
        callback();
    }
}

let st = fs.createReadStream('./com/a.com');
let wr = fs.createWriteStream('./com/b.com');
let c = new com({objectMode: true});
st.pipe(c).pipe(wr);

run it, and got some error. I run it in nodeV6.11.1, but got error:

TypeError: Invalid non-string/buffer chunk
    at validChunk (_stream_writable.js:211:10)
    at WriteStream.Writable.write (_stream_writable.js:241:21)
    at com.ondata (_stream_readable.js:555:20)

anything wrong in my code?

Upvotes: 1

Views: 2192

Answers (1)

mscdex
mscdex

Reputation: 106736

The reason is that while the custom Transform class is correctly configured to input and output any values, the wr Writable stream is expecting Buffers or strings only. So when you push() a non-Buffer/string, you will receive the error you are currently seeing.

If you want to enable object mode for only one side of the Transform stream, then you can set readableObjectMode or writableObjectMode to true instead of objectMode (which is the equivalent of setting the previous two to true).

Upvotes: 1

Related Questions