Home > Software design >  How to create empty (immideately completed) ReadWriteStream in NodeJS?
How to create empty (immideately completed) ReadWriteStream in NodeJS?

Time:03-17

How to create empty NodeJS.ReadWriteStream which will immideately stopped?

If you are interesting why I need to do this, I am developing the function for Gulp, which basically returns NodeJS.ReadWriteStream via Gulp.src(). But under certain conditions, the task must not be executed. The pseudo code is

function provideStylesProcessing(
  config: { /* various settings */ }
): () => NodeJS.ReadWriteStream {
    
    if (/* certain conditions */) {
      Return immideately ended NodeJS.ReadWriteStream
    }


    // Else use Gulp functionality as usual
    return (): NodeJS.ReadWriteStream => Gulp.src(entryPointsSourceFilesAbsolutePaths).
          pipe(/* ... */);
}

You may reccomend "you can return the empty Promise instead". Yes, this is an alternative, but I don't want to complicate the function: if task is steam based, it should return the stream; if callback based - callback (it wrapped to function to allows the adding of parameters) and so on.

CodePudding user response:

You can use any empty duplex stream, for example a dummy PassThrough stream, and end it manually with .end().

const { PassThrough } = require('stream');

function provideStylesProcessing(
  config: { /* various settings */ }
): () => NodeJS.ReadWriteStream {
    
    if (/* certain conditions */) {
      return new PassThrough().end();
    }

    ...
}

CodePudding user response:

You can use a PassThrough stream to do this:

A PassThrough stream is a Transform stream that just passes the data through without transforming it.

import { PassThrough } from 'stream';

const xs = new PassThrough({
  objectMode: true
});

xs.end();

xs.on('finish', () => {
  console.log('This stream has ended');
});

  • Related