0

I have a csv file say like this:

ID   Name   TNumber
123  John   123456
123  Joe    789012
124  Tim    896578
124  Tom    403796

I would like to split it into 2 separate csv files based on the ID column.

I am using fast-csv to parse and other modifications on the csv. I need to split the file into two (in the above case) and then do the other operations. How can I achieve this?

1 Answer 1

3

This works:

const fs = require('fs');
const fastCsv = require('fast-csv');

const datas = {}; // data['123'] = CSV data filtered for id = 123
const options = {headers: true, delimiters: '\t'}; // relative to your CSV usage

fastCsv
    .fromPath('./data.csv', options)
    .on('data', d => {
        if (!datas[d.id]) datas[d.id] = [];
        datas[d.id].push(d)
    })
    .on('end', () => {
        Object.keys(datas).forEach(id => {
            // For each ID, write a new CSV file
            fastCsv
                .write(datas[id], options)
                .pipe(fs.createWriteStream(`./data-id-${id}.csv`));
        })
    });

Additionally this should be quite fast.

Sign up to request clarification or add additional context in comments.

1 Comment

This looks beautifully useful. Unfortunately, when I tried it it output a csv named "data-id-undefined.csv" equivalent to the same tab del file from above. Also tried with comma separated. In FastCsv, aside from fromPath changing to parseFile, what else may keep it from working under Node 12.16.1 from 2020?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.