如何在 NodeJS 中创建空的(立即完成的)ReadWriteStream?

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

如何创建空 NodeJS.ReadWriteStream 将立即停止?

如果你对我为什么需要这样做感兴趣,我正在开发这个功能 对于 Gulp,基本上 returns NodeJS.ReadWriteStream 通过 Gulp.src()。 但在某些条件下,任务不得执行。伪代码为

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

您可能会推荐“您可以 return 空的 Promise 代替”。是的,这是另一种选择, 但我不想使功能复杂化:如果任务是基于 Steam 的,它应该 return 溪流;如果基于回调 - 回调(它包装到函数以允许添加参数)等等。

您可以使用任何空的双工流,例如虚拟 PassThrough 流,并以 .end() 手动结束。

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

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

    ...
}

您可以使用 PassThrough 流来执行此操作:

PassThrough 流是一种仅传递数据而不对其进行转换的转换流。

import { PassThrough } from 'stream';

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

xs.end();

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