Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prepend to a transform stream?

Tags:

stream

node.js

While my example uses Trumpet, this question is valid for any duplex stream.

I'm using trumpet to prepend a chunk of html to the body, but I can't seem to find a reference on how to prepend to a duplex stream.

I read from a file, and then pipe the stream to itself, which works, but then the stream won't end.

  fs.readFile(headerPath, 'utf8', (err, header) => {
    const stream = node.createStream();

    stream.write(header);
    stream.pipe(stream);
    return stream.on('end', () => {
      stream.end('');
    });
  });
like image 978
Amin Shah Gilani Avatar asked Mar 01 '26 16:03

Amin Shah Gilani


1 Answers

You can prepend using the writable's pipe event, which is emitted also in Duplex & Transform streams.

Here is an example with process.stdout (which is a Duplex stream instance):

process.stdout.on('pipe', function() {
  // Prepend some text
  this.write('header');
});

fs.createReadStream(file)
.pipe(process.stdout);
like image 143
Avraham Avatar answered Mar 03 '26 07:03

Avraham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!