James
James

Reputation: 139

How to read a text file if the file has multiple datas in a row those are separated using pipe(|) fs module?

I am trying to read a text file using node js fs module. My first question is , Does fs module support to read only text file or other file formats too ?

Now My main question is if the text file have the data like below, How do i read each data separately in the file ?..Please note some cell in the row could be empty as well.

James|Allister|12345|28|Sunderland|14

Andy|Cook|88888|33|New Jersey|16

Maria|Konsick|44||34 

Upvotes: 0

Views: 73

Answers (1)

generalhenry
generalhenry

Reputation: 17319

The fs module doesn't understand file formats, it just reads buffers. Optionally it can convert the buffers into strings. As for that file, it's a csv just with | instead of ,.

Parsing it is somethings like:

// split the lines into rows
const rows = raw.split('\n');
// split into columns
const data = rows.map(row => row.split('|'));

The empties will just be empty strings in the row arrays. You can filter them out. rows.map(row => row.split('|').filter(el => el !== '')) but most likely you'll want to leave them in for easy access my index.

But that assumes there are no escapes or other irregularities. I recommend finding a csv module from npm.

Upvotes: 1

Related Questions