2
\$\begingroup\$

As the title says, I'm loading (or at least trying to) two CSV files and store them in two separate arrays. What I have so far worked, but it isn't the most elegant, no efficient solution.

The end goal is to read in two CSV files and run comparisons on them both - that's why the separating them is important.

Note - I use the csv-parser library, but am open to different solutions.

const express = require("express");
const parse = require("csv-parser");
const fs = require("fs");
const app = express();
const port = 3000;
var CSVOne = [];
var CSVTwo = [];
fs.createReadStream("public/activity.csv")
 .pipe(parse())
 .on("data", data => CSVOne.push(data))
 .on("end", () => {
 sender = CSVOne.map(d => {
 return {
 email: d.Sender
 };
 });
 fs.createReadStream("public/groups.csv")
 .pipe(parse())
 .on("data", dataTwo => CSVTwo.push(dataTwo))
 .on("end", () => {
 one = CSVTwo.map(d => {
 return {
 clinic: d.one
 };
 });
 console.log(sender);
 console.log(one);
 });
 });
app.listen(port, function() {
 console.log("Server has started");
});
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 12, 2019 at 15:32
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I don't know about elegant, but you could load the files in parallel for better performance. To do something when all CSV files are ready you can use promises or just a simple counter.

The example also shows how you can use objects as return value in your arrow functions without the extra { return {...} }.

Example of loading in parallel using the counter method:

const express = require("express");
const parse = require("csv-parser");
const fs = require("fs");
const app = express();
const port = 3000;
var CSVOne = [];
var CSVTwo = [];
var toGo = 2;
fs.createReadStream("public/activity.csv")
 .pipe(parse())
 .on("data", data => CSVOne.push(data))
 .on("end", () => {
 sender = CSVOne.map(d => ({
 email: d.Sender
 }));
 maybeDone();
 });
fs.createReadStream("public/groups.csv")
 .pipe(parse())
 .on("data", dataTwo => CSVTwo.push(dataTwo))
 .on("end", () => {
 one = CSVTwo.map(d => ({
 clinic: d.one
 }));
 maybeDone();
 });
function maybeDone() {
 toGo -= 1;
 if (toGo === 0)
 done();
}
function done() {
 console.log("Both CSV files are ready");
 console.log(CSVOne, CSVTwo);
}
app.listen(port, function() {
 console.log("Server has started");
});
dfhwze
14.1k3 gold badges40 silver badges101 bronze badges
answered Jul 13, 2019 at 1:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.