0

我有这个 csv 文件:

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

要将其存储在 txt 文件中:

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

这是学校的作业,我们需要使用 csv-parser。

4

1 回答 1

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);
于 2022-01-24T11:33:30.547 回答