Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Spatial Database Systems Design Implementation And Project Management

Authors: Albert K.W. Yeung, G. Brent Hall

1st Edition

1402053932, 978-1402053931

More Books

Students also viewed these Databases questions

Question

2. How will you handle the situation?

Answered: 1 week ago

Question

3. Write a policy statement to address these issues.

Answered: 1 week ago