Open dbvz opened 1 year ago
Reading files line by line can be done using readLines function.
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.
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.
@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.
It works now
Ok. So now let's do some coding!
typeof fileContent
? Check it.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.
fileContent
into multiple lines, write a for
-loop to convert each line into a User
object.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"
}
]