YaroslavUsheta / Javascript-playground

Learning JS
2 stars 0 forks source link

Reading CSV file #6

Open dbvz opened 1 year ago

dbvz commented 1 year ago
  1. Create new folder and create a csv file (stands for coma separated values). Here is the example (save it as users.csv, for instance):
id, first name, last name, title
1, Scott, Hunter, VP of Azure Development
2, Scott, Guthrie, EVP of Azure & AI
3, Scott, Hanselman, Director of Azure
  1. Create a script that would read this file line by line into an array of users. Here user is an object defined by the first line, the header, of the csv file. The script should read name of the file from the input.
  2. Print users as a table to the screen.
dbvz commented 1 year ago

Reading files line by line can be done using readLines function.

dbvz commented 1 year ago

This line import { open } from 'node:fs/promises'; will not work in a standalone script. We need to setup a proper node project for this to work.

dbvz commented 1 year ago

I have created a starting point for you. cd into reading-csv folder and run rpm run test in the terminal. It should print the content of the file.

dbvz commented 1 year ago

@YaroslavUsheta, I know why it does not work. I used the very latest version of node. And you have a different version installed on your machine. That version simply does not have readLines function. And node reports correct error message. Replace file content with the following:

import { open } from "node:fs/promises";

const file = await open("./users.csv");

const fileContent = await file.readFile({ encoding: 'utf8' });

console.log(fileContent);

Run it using npm run test and it should print the content of the file.

YaroslavUsheta commented 1 year ago

It works now

dbvz commented 1 year ago

Ok. So now let's do some coding!

  1. What is typeof fileContent? Check it.
  2. It's a single string isn't it? We need to convert it to the array of strings. One string per line. To do that try using split method. Find its documentation. You need to split the string at a new line character \n. Try printing the following string to the console: First line.\nSecond line.. It should appeal like this:
    First line.
    Second line.
  3. After you split fileContent into multiple lines, write a for-loop to convert each line into a User object.
dbvz commented 1 year ago
const lineBreak = "\n";

// for await (const line of file.readLines()) {
//   console.log(line);
// }

console.log(fileContent.split(lineBreak));

const firstLine = fileContent.split(lineBreak)[1];

console.log("Printing the first line");

console.log(firstLine.split(','));

and

const users = [
  {
    id: 1,
    firstName: "Scott",
    lastName: "Hunter",
    title: "VP of Azure Development"
  },
  {
    id: 1,
    firstName: "Scott",
    lastName: "Hunter",
    title: "VP of Azure Development"
  }
]