nodejs and streams piping

Viewed 478

I have a question about pipes in nodejs. I have some code, that should display list of files in current directory, but it works unexpectedly.

const { Transform, PassThrough, Readable } = require("stream");

const fs = require("fs");
const config = {distPath: '.',scanPath: '.'};

let writeStream = process.stdout;

let pass = new PassThrough();

fs.readdir(config.scanPath, (err, files) => {
    files.forEach(file => {        
        let filename = new Readable();
        filename.push(file + "\n");
        filename.push(null);
        filename.pipe(pass).pipe(writeStream);
    });
});

First of all, i know how to change code for correct work. I just want to understand why this code works so.

The code is simple, one writable stream, and many readable streams in loop wants to write data to it through PassTrough. If i will remove pipe, all works as expected. i see list of files that are in current directory. But with pipe, all names are duplicated as many times as many files are in directory + 1.

Why filenames are duplicated with pipe?

1 Answers
Related