0

I have a CSV file as below - accounts.csv

User_Name,Password
TestAccount1,Passw0rd
TestAccount2,Passw0rd
TestAccount3,Passw0rd
TestAccount4,Passw0rd

Trying to write a JavaScript code to read them into a array variable and use it further in script like UserName[1] and Password [1] or may be like UserName and Password

Tried using the below code:

const fs = require('fs');
var parse = require("csv-parse"); //installed csc-parse
var csvFile = "accounts.csv";

class User {
  constructor(user_id, user_password) {
    this.user_id = user_id;
    this.user_password = user_password;
  }
}

const processData = (err, data) => {
  if (err) {
    console.log(`An error was encountered: ${err}`);
    return;
  }

  //skipping has heading row
  data.shift(); 

  const userList = data.map(row => new User(...row));

}

fs.createReadStream(csvFile)
  .pipe(parse({ delimiter: ',' }, processData));
user127911
  • 35
  • 5
  • 1
    Does this answer your question? [How to read data From \*.CSV file using javascript?](https://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript) – Justinas Jun 10 '20 at 13:08

1 Answers1

2

Try the below snippet :

const fs = require('fs');
var parse = require("csv-parse"); //installed csv-parse
var csvFile = "accounts.csv";
const userList = [];

const processData = (data) => {
    if (data != undefined) {
        //console.log(data);
        userList.push({ "username" : data[0],   "password" : data[1]});
    }
}

fs.createReadStream(csvFile)
    .pipe(parse({
        delimiter: ',',
        from_line: 2 // to skip the header row
    }, processData))    
    .on('data', processData)
    .on('end', () => {
        console.log('CSV file successfully processed');
        console.log(userList);
    });
Nareen Babu
  • 443
  • 1
  • 5
  • 13
  • Thanks, I have tried the shared code, it gives me output as: `code` [ 'TestAccount1', 'Passw0rd' ] [ 'TestAccount2', 'Passw0rd' ] CSV file successfully processed [ User { User_Name: 'TestAccount1', Password: 'Passw0rd' }, User { User_Name: 'TestAccount2', Password: 'Passw0rd' } ] `code` What I am looking for is 2 variables, something like: `code` console.log(username); console.log(password); Output: TestAccount1 Passw0rd `code` – user127911 Jun 11 '20 at 01:22
  • @user127911 - You want the output like `[{ "U1" : "P1"},{"U2":"P2"}]` or You want it like `UserName & Password` in `seperate Array` ? – Nareen Babu Jun 11 '20 at 04:20
  • My objective is to read User ID and Password from CSV and use it in POST body for Login using JavaScript (as part of SiteSpeed.io scripting) Given the post body, I am looking to have an Array (may be 1 or 2), using which I can substitute User and Password individually, somewhat like below: `code` ID='username' value= ID='password' value= – user127911 Jun 11 '20 at 06:53
  • @user127911 - Modified the above snippet - Is this you are looking for ? – Nareen Babu Jun 11 '20 at 07:19