简体   繁体   English

Node.js和流管道

[英]nodejs and streams piping

I have a question about pipes in nodejs. 我对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. 该代码很简单,一个可写流,并且循环中的许多可读流都希望通过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. 但是,使用管道时,所有名称的重复次数是目录+ 1中文件的重复次数。

Why filenames are duplicated with pipe? 为什么文件名与管道重复?

After some research i have an answer. 经过一些研究,我有一个答案。 It's because of 'pass' in both cases the same object, and it has 2 (or more, depends on files count) streams piped for write (in this case 2 or more the same streams). 这是因为在两种情况下都是同一对象的“通过”,并且它有2个(或更多,取决于文件数)管道被写入写入(在这种情况下,有2个或更多相同的流)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM