简体   繁体   中英

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 

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 collumns
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM