I have a CSV file and I need to display in the terminal only the second column. I'm using javascript and nodejs. My CSV file is in a local folder. My CSV data look like this:
name,emails,name1,email1,name2,email2,name3,email3,name4,email4,name5,email5
It's like an array with two columns and six rows, first one with name and second one with emails. I only want to return the list of emails without the heading in the terminal. Later I'll have to use this email list to compare it with an other array.
I think it is possible with papaparse
but I don't understand how to use it.
I also know that fs
module can be use to read the entire file.
If it's possible to convert the data in an array with or without keys/values like this it will also be perfect:
[ name:'name1', email:'email1', name:'name2', email:'email2', name:'name3', email:'email3', name:'name4', email:'email4', name:'name5', email:'email5' ]
Knowing that I also have to do it with an other CSV file that contain 9 columns and 960 rows.
This code should parse a CSV file in the format you mention, e.g.
test.csv
name,emails name1,email1 name2,email2 name3,email3 name4,email4 name5,email5
app.js
const Papa = require('papaparse');
const fs = require("fs");
let csvData = fs.readFileSync("test.csv", "utf-8");
csvData = csvData.trim().replace(/([^,]+),\s*([^,]+),\s*/gi, '$1,$2\n');
console.log("Adjusted csv:", csvData);
let { meta, data } = Papa.parse(csvData, { header: true });
console.log("Parsed data:", data);
console.log("Metadata:", meta);
The parsed data would look like so:
[
{ name: 'name1', emails: 'email1' },
{ name: 'name2', emails: 'email2' },
{ name: 'name3', emails: 'email3' },
{ name: 'name4', emails: 'email4' },
{ name: 'name5', emails: 'email5' }
]