DEV Community

Read CSV File using Node JS

Mahesh K on August 09, 2018

I am currently working on a business project that exports the processed data to CSV file. I wanted to process that into the dashboard. I can choos...
Collapse
 
itsasine profile image
ItsASine (Kayla) • Edited

I just use fs.

require('fs');
// ...
readFile: function(path) {
    var fileContent;

    return new Promise(function(resolve) {
        fileContent = fs.readFileSync(path, {encoding: 'utf8'});
        resolve(fileContent);
    });
}

When I use the contents of the file, it's like

stuff,stuff,stuff,stuff,stuff\r\n
thing,thing,thing,thing,thing\r\n
thing,thing,thing,thing,thing\r\n
thing,thing,thing,thing,thing\r\n
thing,thing,thing,thing,thing\r\n
thing,thing,thing,thing,thing

which is good enough for my purposes.

Collapse
 
anh3h profile image
Ang3h Courage

typo: fileContent = fs.readFileSync(path, {encoding: 'utf8'});

Collapse
 
itsasine profile image
ItsASine (Kayla)

Fixed it now, thanks :)

Collapse
 
isalevine profile image
Isa Levine

Hi Kayla, this is awesome! Do you mind if I link to this code snippet in a CSV-parsing dev.to article I'm working on? I'd love to include a purely fs solution. :)

Collapse
 
itsasine profile image
ItsASine (Kayla)

Go for it! :)

Thread Thread
 
isalevine profile image
Isa Levine

Thank you!! Here's the link to the article, with the link to your snippet in the conclusion. :)

dev.to/isalevine/parsing-csv-files...

Collapse
 
tahorsuijuris profile image
TahorSuiJuris

Question, please:

Why does this only return the first character of the string?

    const searchkeywords = fs.readFileSync('kwords.csv','utf-8');
        for (let kword of searchkeywords) {
    console.log(`Search Keyword: ${kword}`);

Text for the first 10 rows is:

"1-800-FLOWERS.COM, INC.",
"1ST SOURCE",
"1ST SOURCE CORP",
"3D SYSTEMS",
"8X8, INC.",
"A.H. BELO",
"AAON",
"AARON RENTS",
"ABERCROMBIE & FITCH",
"ABIOMED",

Collapse
 
ignoreintuition profile image
Brian Greig

I generally prefer to use something like csvtojson and get it into a format that is easier to parse.

Collapse
 
stevehsu profile image
Steve Hsu

Thanks! It saved me.

Collapse
 
abusedmedia profile image
Fabio Franchino

I wrote an article a while ago possibly related: fabiofranchino.com/blog/merging-cs...

Collapse
 
maheshkale profile image
Mahesh K

This is handy for sure. Thanks a lot.