首页 > 解决方案 > 如何使用 fs.writeFile 格式化 csv 文件

问题描述

我有一个看起来像这样的 CSV 文件

CSV 文件:

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

我首先读取 csv 中的文件,并将所有内容放入数组中

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')

我需要这样格式化结果:

* 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

并使用输出它们fs.writeFile

标签: javascriptnode.js

解决方案


假设您从读取 CSV 文件中获得了一系列项目:

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']
]
*/

首先,我们可以创建两个单独的数组来存储午餐项目和晚餐项目。

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

接下来我们可以遍历菜单,并将每一行放入适当的列表中

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);
  }
});

(参见Array.forEachArray.slice


现在使用您的两个列表,您可以创建文本文件。如果你想从午餐开始:

let menu_text = '* Lunch Items *';

您想在文本中将每个项目附加为换行符,您可以使用\n表示换行符的字符来执行此操作。循环遍历数组,并将每个项目添加到字符串中:

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

(见模板文字


对于晚餐,您需要添加两条新行,以便午餐和晚餐项目之间存在间隙:

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

现在我们使用相同的循环技术来添加晚餐项目

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

最后,您可以将新创建​​的文本输出为 txt 文件。

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

推荐阅读