A javascript CSV parser that reads a file.
const csv = require("csv-stream"); //requires npm install
const fs = require("fs");
var options = {};
class RowObject {
constructor() {
this.weekdays = [];
this.times = [];
}
}
let currentKey = "";
let myMap = new Map();
const csvStream = csv.createStream(options);
fs.createReadStream(
"//Users/nmarotta/Desktop/nodestuff/csvfilewithheaders.csv"
)
.pipe(csvStream)
.on("error", function(err) {
//console.error(err);
})
.on("header", function(columns) {
//console.log(columns);
})
.on("data", function(data) {
// outputs an object containing a set of key/value pair representing a line found in the csv file.
//console.log(data);
})
.on("column", function(key, value) {
// outputs the column name associated with the value found
key = key.trim();
value = value.trim();
if (key === "function_type" && currentKey !== value) {
currentKey = value;
if (!myMap.has(currentKey)) {
myMap.set(currentKey, new RowObject());
}
}
if (key === "weekdayName") {
let curWeekday = shortenWeekday(value);
let curWeekdayList = myMap.get(currentKey).weekdays;
if (!curWeekdayList.includes(curWeekday)) {
curWeekdayList.push(curWeekday);
}
}
if (key === "scheduleTime") {
let curTime = value;
let curTimeList = myMap.get(currentKey).times;
if (!curTimeList.includes(curTime)) {
curTimeList.push(curTime);
}
}
//console.log("#" + key + " = " + value);
})
.on("close", () => {
for (let key of myMap.keys()) {
console.log(
key.toString() +
"," +
myMap.get(key).weekdays.join(" ") +
"," +
myMap.get(key).times.join(" ")
);
}
});
function shortenWeekday(weekday) {
let day = "";
switch (weekday) {
case "Sunday":
day = "Sun";
break;
case "Monday":
day = "Mon";
break;
case "Tuesday":
day = "Tues";
break;
case "Wednesday":
day = "Wed";
break;
case "Thursday":
day = "Thurs";
break;
case "Friday":
day = "Fri";
break;
case "Saturday":
day = "Sat";
}
return day;
}