'How to create empty (immideately completed) ReadWriteStream in NodeJS?

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.



Solution 1:[1]

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

    ...
}

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 vamsiampolu