javascript - 如何使用 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
解决方案
假设您从读取 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);
}
});
现在使用您的两个列表,您可以创建文本文件。如果你想从午餐开始:
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.
})
推荐阅读
- javascript - 有什么方法可以优化这个反应应用程序,可能呈现数百万个组件
- c++ - 乘以 std::complex
通过模板化运算符重载加倍 - asp.net-core - 最大索赔数量
- java - 将在同步语句之前在另一个同步诺克之前?
- bit-manipulation - 给定并行中多个整数的索引,AVX或其他可以提取特定位的设置指令?
- c++ - 为什么 std::mutex 需要很长时间才能共享?
- mysql - MYSQL - FK存在和不存在时的SubSelect
- php - 如何在远程服务器上从 php 调用 python
- elasticsearch - 如何结合 Elastic Search 中的过滤器编写嵌套查询?
- tableau-api - 在画面中按日期识别下一个最接近的记录