data into txt file
Computer Science
NODEJS
How do I read specific data from csv file (for example extract data only from Canada and United States) and put that into a variable and then make a txt file and use that variable to put that data into txt file? Here is what I have so far below, I'm struggling with the ////grab data for canada section. Thanks for helping.
const csv = require('csv-parser');
const fs = require('fs');
const inputs = [];
//use csv parser
fs.createReadStream('input_countries.csv')
.pipe(csv())
.on('data', (row) => {
inputs.push(row);
})
.on('end', () => {
console.log('CSV file successfully processed');
});
console.log("Deleting canada.txt file if it exists");
fs.unlink('canada.txt', function (err) {
if (err) {
return console.error(err);
}
console.log("canada.txt deleted sucessfully")
});
console.log("Deleting usa.txt file if it exists");
fs.unlink('usa.txt', function (err) {
if (err) {
return console.error(err);
}
console.log("usa.txt deleted sucessfully")
});
const header = ['country,year,population']
const Canada = [];
const USA = [];
//grab data for canada and usa
inputs.forEach((input) => {
if (input.country == 'Canada')
Canada.push(`${input.country},${input.year},${input.population}`);
if (input.country == 'United States')
USA.push(`${input.country},${input.year},${input.population}`);
});
//write data to txt file
fs.writeFile('canada.txt', Canada.join('\n'), (err) => {
if (err) {
console.log('error writing data to canada.txt', err);
}
else {
console.log('saved data to canada.txt sucessfully')
}
})
fs.writeFile('usa.txt', USA.join('\n'), (err) => {
if (err) {
console.log('error writing data to usa.txt', err);
}
else {
console.log('saved data to usa.txt sucessfully')
}
}.
Step by step
Solved in 2 steps with 2 images