Question: 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

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(' '), (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(' '), (err) => {

if (err) {

console.log('error writing data to usa.txt', err);

}

else {

console.log('saved data to usa.txt sucessfully')

}

})

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!