Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple transform stream into one in nodejs

Tags:

stream

node.js

I have following code snippet

function func1(){
  return  makeReadbleStream1()
    .pipe(transformA)
    .pipe(transformB)
    .pipe(transformC)
    .pipe(X);
}

function func2(){
  return  makeReadbleStream2()
    .pipe(transformA)
    .pipe(transformB)
    .pipe(transformC)  
    .pipe(Y);
}

Function 1 and 2 shares a common logic of going through the transform A, B and C. Based on the principle of DRY, I think it's better to extract the logic into a function combinedTransformABC. However, it seems to me no obvious way to implement this function based on transformA, B and C such that I could refactor the code as below.

function func1(){
  return  makeReadbleStream1()
    .pipe(combinedTranformABC)
    .pipe(X);
}

function func2(){
  return  makeReadbleStream2()
    .pipe(combinedTranformABC)
    .pipe(Y);
}    

Any idea?

like image 940
victorx Avatar asked Oct 19 '22 22:10

victorx


1 Answers

Why not just do this:

function applyTransforms(stream){
    return stream.pipe(transformA)
        .pipe(transformB)
        .pipe(transformC);
}
function func1(){
    return applyTransforms(makeReadbleStream1()).pipe(X);
}
function func2(){
    return applyTransforms(makeReadbleStream2()).pipe(Y);
}
like image 138
codebox Avatar answered Oct 22 '22 12:10

codebox