I'm trying to get the headers of a csv file into an array and attempting to use the csv-parser to do so. Two things I can't figure out here:
1) Why is the console.log on the last line of the code firing before anything else? This also means the variable's value I'm attempting to log is undefined.
2) Why isn't my getFields function returning the newly filled array of headers? I can console.log the results array with all of its new elements from inside the function, but I can't actually return the array full of elements--it keeps returning an empty array.
Here's the code:
const express = require('express')
const app = express()
const port = 3000
const csv = require('csv-parser')
const fs = require('fs')
function getFields (filePath) {
let results = [];
fs.createReadStream(filePath)
.pipe(csv())
.on('headers', (headers) => {
let values = Object.values(headers);
values.forEach(function(element) {
results.push(element);
});
console.log('I am actually getting results here: ', results);
return results;
});
}
const omg = getFields(thisIsAFilePath)
console.log('This console.log is firing before anything else: ', omg)