简体   繁体   中英

how to format a csv file with fs.writeFile

I have a CSV file that look like this

CSV file:

lunch,bento box b - sashimi,box combo,$9.59
dinner,vegetable sushi,6 rolls,$3.50
dinner,tuna roll,3 rolls,$4.50
dinner,roe,2 rolls,$3.95
lunch,bento box a - chicken teriyaki,box combo,$8.59

I first read the file in the csv, and put everything in a array

function getMenu (fileName) {
    fs.readFile (fileName, 'utf8', (err,data)=>{
        if (err){
            console.log (err.message)
        }
        let arr = []
        let myMenu = data.trim().split('\n')
        for (const item of myMenu) {
            arr.push (item.split(","))
        }
        console.log (arr)
    })
}


 getMenu ('meals.csv')

I need to format the results this this:

* Lunch Items *
$15.46  bento box a - chicken teriyaki, box combo  
$17.26  bento box b – sashimi, box combo  

* Dinner Items *
 $7.11  roe, 2 rolls   
 $8.10  tuna roll, 3 rolls  
 $6.30  vegetable sushi, 6 rolls

And output them using fs.writeFile

Assume you have an array of items from your reading of the CSV file:

let arr = getMenu('meals.csv');

/*
arr = [
  ['lunch','bento box b - sashimi', 'box combo', '$9.59'],
  ['dinner','vegetable sushi', '6 rolls', '$3.50'],
  ['dinner','tuna roll', '3 rolls','$4.50'],
  ['dinner','roe','2 rolls','$3.95'],
  ['lunch','bento box a - chicken teriyaki', 'box combo','$8.59']
]
*/

First we can create two seperate arrays to store lunch items and dinner items.

let lunch = [];
let dinner = [];

Next we can loop over the menu, and place each row into the appropriate list

arr.forEach(item => {
  let item_without_category = item.slice(1);

  if (item[0] === 'lunch') {
    lunch.push(item_without_category);
  }
  else {
    dinner.push(item_without_category);
  }
});

(See Array.forEach , and Array.slice )


Now with your two lists you can create the text file. If you want to start with lunch:

let menu_text = '* Lunch Items *';

You want to append each item as a newline in the text, you can do this with the \n character which means newline. Loop over the array, and add each item to the string:

lunch.forEach(item => {
  menu_text += `\n${item[2]}  ${item[0]}, ${item[1]}`;
});

(See Template Literals )


For dinner, you need to add two new lines so that there is a gap between lunch and dinner items:

menu_text += '\n\n* Dinner Items *';

Now we use the same looping technique to add the dinner items

dinner.forEach(item => {
  menu_text += `\n${item[2]}  ${item[0]}, ${item[1]}`;
});

Then finally, you can output your newly created text as a txt file.

fs.writeFile('menu.txt', menu_text, (err) => {
  // Do whatever you want when you're done here.
})

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