0

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.

MKOCH
  • 45
  • 1
  • 5

1 Answers1

0
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);
traynor
  • 5,490
  • 3
  • 13
  • 23