Search code examples
node.jscsv-parser

How can I read a csv file and store it in a txt file using specifically csv-parser


I have this csv file:

country,year,population
USA,1952,8425333
USA,1957,9240934
...

want to store it in a txt file:

country,year,population
USA,1952,8425333
USA,1957,9240934
...

This is an assignment for school and we are required to use csv-parser.


Solution

  • const csv = require('csv-parser');
    const fs = require('fs');
    
    
    const csvFile = fs.createReadStream('csv.csv');
    const txtFile = fs.createWriteStream('txt.txt');
    
    const csvParser = csv();
    
    let head = false;
    
    csvParser.on('data', function(data) {
    
            if (!head) {
                txtFile.write('country,year,population\r\n');
                head = true;
            }
    
            const {country, year, population } = data;
    
            const row = `${country},${year},${population}\r\n`;
    
            txtFile.write(row);
    
        })
        .on('end', function() {
            console.log('no pain, no gain');
        })
        .on('error', function(error) {
            console.log(error);
        });
    
    csvFile.pipe(csvParser);