如何读取 csv 文件并将其存储在 txt 文件中,专门使用 csv-parser
How can I read a csv file and store it in a txt file using specifically csv-parser
我有这个 csv 文件:
country,year,population
USA,1952,8425333
USA,1957,9240934
...
想保存在txt文件中:
country,year,population
USA,1952,8425333
USA,1957,9240934
...
这是学校的作业,我们需要使用 csv-parser。
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);
我有这个 csv 文件:
country,year,population
USA,1952,8425333
USA,1957,9240934
...
想保存在txt文件中:
country,year,population
USA,1952,8425333
USA,1957,9240934
...
这是学校的作业,我们需要使用 csv-parser。
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);