Search code examples
node.jsgulp

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

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