Amin Shah Gilani
Amin Shah Gilani

Reputation: 9866

How do I prepend to a transform stream?

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('');
    });
  });

Upvotes: 3

Views: 1076

Answers (1)

Avraham
Avraham

Reputation: 938

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);

Upvotes: 2

Related Questions