Skip to content

[Replacement]: sandwich-stream #549

@gameroman

Description

@gameroman

Package to replace

sandwich-stream

Suggested replacement(s)

node:stream

For example:

Original

import { SandwichStream } from 'sandwich-stream';
// OR EVEN:
// const SandwichStream = require('sandwich-stream');

const sandwich = SandwichStream({
    head: 'Thing at the top\n',
    tail: '\nThing at the bottom',
    separator: '\n ---- \n'
});

sandwich.add(aStreamIPreparedEarlier)
        .add(anotherStreamIPreparedEarlier)
        .add(aFurtherStreamIPreparedEarlier)
        .pipe(process.stdout);

// The thing at the top
//  ---- 
// Stream1
//  ---- 
// Stream2
//  ---- 
// Stream3
// The thing at the bottom

Replacement 1

import { Readable } from 'node:stream';

async function* createSandwich(streams, { head, tail, separator }) {
  if (head) yield head;

  for (let i = 0; i < streams.length; i++) {
    // Yield all data from the current stream
    yield* streams[i];
    
    // If there is another stream coming, yield the separator
    if (separator && i < streams.length - 1) {
      yield separator;
    }
  }

  if (tail) yield tail;
}

// Usage:
const streams = [
  aStreamIPreparedEarlier,
  anotherStreamIPreparedEarlier,
  aFurtherStreamIPreparedEarlier
];

const sandwich = Readable.from(createSandwich(streams, {
  head: 'Thing at the top\n',
  tail: '\nThing at the bottom',
  separator: '\n ---- \n'
}));

sandwich.pipe(process.stdout);

Replacement 2

import { compose } from 'node:stream';

const sandwich = compose(async function* () {
  yield 'Thing at the top\n';
  
  yield* aStreamIPreparedEarlier;
  yield '\n ---- \n';
  
  yield* anotherStreamIPreparedEarlier;
  yield '\n ---- \n';
  
  yield* aFurtherStreamIPreparedEarlier;
  
  yield '\nThing at the bottom';
});

sandwich.pipe(process.stdout);

Manifest type

preferred (lighter or more modern alternative package)

Rationale

Can be replaced with native functionality

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions