简体   繁体   中英

Node.js transform stream only passes through data as-is

I'm trying to create a little Node.js app that can read Markdown text and converts it to HTML. To achieve this, I wanted to create a transform stream that would get a char at a time, figure the meaning, then return the HTML version of it.

So, for example, if I pass the transform stream a *, it should return <b> (or </b> ).

However, the Transform stream does not actually transform data, whatever I push to it, it just comes back like I pushed it, and when I put a console.log statement into the transform method of the stream, I saw no output, as if the method isn't even called.

Here's the file with the Stream:

module.exports = function returnStream() {

const Transform = require('stream').Transform;

let trckr = {
    bold: false
};

const compiler = new Transform({
    transform(chunk, encoding, done) {
        const input = chunk.toString();
        console.log(input); // No output
        let output;

        switch (input) {
          case '*':
            if (trckr.bold === true) {
              output = '</b>';
              trckr.bold = false;
            } else {
              output = '<b>';
              trckr.bold = true;
            }

            break;

        default:
            output = input;
    }

    done(null, output);
  }
});

  return compiler;

};

Example file that uses the Stream:

const transformS = require('./index.js')();

transformS.on('data', data => {
  console.log(data.toString());
});

transformS.push('*');

Thanks!

done(null, output) and transformS.push() are performing the exact same function: they push data to the readable (the output) side of the Transform stream. What you need to do instead of calling transformS.push() is to write to the writable (the input) side of the Transform stream with transformS.write('*') .

I should also point out that you should not make assumptions about the contents of chunk in your transform function. It could be a single character or a bunch of characters (in which case input may never equal '*' ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM