简体   繁体   English

处理嵌套流

[英]Processing nested streams

I am trying to generate an output file by joining 2 csv input streams, for each record in csv 1 I want to generate an output for each record in csv 2. 我试图通过连接2个csv输入流来生成输出文件,对于csv 1中的每个记录,我想为csv 2中的每个记录生成一个输出。

I came across highland while browsing stack overflow for any similar solutions and came across: 在浏览任何类似解决方案的堆栈溢出时,我遇到了高地,并遇到:

Nested stream operations in Highland.js Highland.js中的嵌套流操作

I have attempted to adjust this to my own problem and so far have this: 我试图将此调整为我自己的问题,到目前为止:

    const debug = require('debug')('csvparse');
    const csv = require('fast-csv');
    const fs = require('fs');
    const args = process.argv;
    const h = require('highland');

    const typestream = h(fs.createReadStream(args[2]).pipe(csv({ headers: true, ignoreEmpty: true })));
    const postcodestream = h(fs.createReadStream(args[3]).pipe(csv({ headers: true, ignoreEmpty: true })));

    const pipeline = typestream.flatMap((type) => {
        debug(type);

        return postcodestream.flatMap((postcode) => {
            debug(postcode);

            return h([`${type.type}-${postcode.postcode}\n`]);
        });
    });

    pipeline.pipe(process.stdout);

With the following example inputs csv1: 使用以下示例输入csv1:

type,
STREET,
ROAD,

csv2: CSV2:

postcode,
3456
3446
1234

Id expect output of 我期望输出

STREET-3456
STREET-3446
STREET-1234
ROAD-3456
ROAD-3446
ROAD-1234

But Im just getting: 但我刚刚得到:

STREET-3456
STREET-3446
STREET-1234

I can see from the debug statements that i get the out of ROAD once and then it stops. 我可以从调试语句中看到,我从ROAD中获取一次然后停止。

Ok I figured out my problem, basically I should have been using through for the csv parsing instead of wrapping the pipe and I shoudl have also been creating the fs.createReadStream within the initial flatMap rather then referencing it from a variable (as the stream will have finished after the initial iteration). 好吧我弄清楚了我的问题,基本上我应该一直使用csv解析而不是包装管道而且我已经在初始flatMap中创建fs.createReadStream而不是从变量引用它(因为流将在最初的迭代后完成)。

Code is now: 代码现在是:

#!/usr/bin/node
const debug = require('debug')('csvparse');
const csv = require('fast-csv');
const fs = require('fs');
const args = process.argv;
const h = require('highland');

const pipeline = h(fs.createReadStream(args[2]))
    .through(csv({ headers: true, ignoreEmpty: true }))
    .flatMap((type) => {
        return h(fs.createReadStream(args[3]))
            .through(csv({ headers: true, ignoreEmpty: true }))
            .map((postcode) => {
                return `${type.type}-${postcode.postcode}\n`;
            });
    });

pipeline.pipe(process.stdout);

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

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