简体   繁体   中英

Pipe a transform or readable stream to process.stdout

I have the following code:

const pt = require('prepend-transform').default;
const writable = pt('[test-process]').pipe(process.stdout);

writable is the destination stream which is process.stdout, so if I write to writable, I just get stdout, without '[test-process]' prepended to each line. Note that pt(x) returns a transform stream.

On the other hand, if I do this instead:

const pt = require('prepend-transform').default;
const transform = pt('[test-process]');
transform.pipe(process.stdout);

and then I write to transform stream, no data seems to make it to process.stdout.

So I do I need to use a read stream instead of a transform stream to do this?

So instead of a transform stream, I tried using a readable stream:

  const data = [];
  const readable = new stream.Readable({
    read: function (size) {
     this.push(data.pop());
    }
  });

 readable.pipe(pt('[test-process]')).pipe(process.stdout);


 let log = function(){
     Array.from(arguments).forEach(function(a){
        data.push(a);
     });
  };

nothing gets written to stdout when I use readable like so.

Using 'prepend-transform' with a Readable Stream


If you do :

const PT =  require('prepend-transform')
console.log(PT)

You get :

{ default: [Function: default_1] }

So, you would have to do PT.default('[test-process]')

Here is a working code example (with readable stream) :

//:Example Readable Stream
var Readable = require('stream').Readable;
var rs = new Readable;
rs.push('beep ');
rs.push('boop\n');
rs.push(null);
//:PrependTransform Correct Usage Example
const PT =  require('prepend-transform');
rs.pipe(PT.default('[child stdout]')).pipe(process.stdout);

Example Output :

[child stdout]beep boop

EXTRA : Node.js : Stream Handbook

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