javascript - 使用 Javascript 和节点 csv-parse 将 csv 文件解析为数组
问题描述
我有一个项目,我必须处理输入 CSV 文件并将其存储到可以添加的数组中,然后将其打印到 CSV 文件中。然后,我将事务数据用于我的项目的其余部分,因此能够完成这部分至关重要,因为将使用其他 CSV 文件执行测试。
我的问题是,在使用 csv-parse 时,如果我使用 console.table(results); 当我在命令终端中运行 .js 文件时,它会显示 csv 对象,因此我知道它的解析,但无论我做什么,我都无法让对象进入我的数组变量。
请有人给我一个关于我哪里出错的提示:
var fs = require('fs');
var parse = require('csv-parse');
var transactionValues = []; //Need an array to hold transactions
//constuctor for transactions
function addData (id, accountType, initiatorType, dateTime, transactions) {
var data = {
"AccountID" : id,
"AccountType" : accountType,
"InitiatorType" : initiatorType,
"DateTime" : dateTime,
"TransactionValues" : transactions
}
transactionValues.push(data); //should add a new line
}
var parser = parse({columns: true}, function (err, results) {
console.table(results);
addData(results.index[0].AccountID, results.index[0].AccountType, results.index[0].InitiatorType, results.index[0].DateTime, results.index[0].TransactionValue, 0);
}); //attempted to save the objects into the array but no success
fs.createReadStream(__dirname+'/testData/customer-1234567-ledger.csv').pipe(parser)
console.log(transactionValues); // array is empty
解决方案
我相信results
它已经是一个正常的数组,因为它是从 csv-parse 返回的。您正在尝试使用 访问第一个元素results.index[0]
,但它只是results[0]
. 另一个问题是fs.createReadStream(...).pipe(...)
异步的。这意味着您console.log
将在解析完成之前运行。您需要将解析后必须运行的任何代码放入parse
函数的回调中。像这样的东西:
var parser = parse({columns: true}, function (err, results) {
console.table(results);
for (const row of results) { //loop through each object parsed from the csv
addData(row.AccountID, row.AccountType, row.InitiatorType, row.DateTime, row.TransactionValue, 0);
}
console.log(transactionValues); // this should be populated properly
/* Do anything that needs to use transactionValues here */
});
推荐阅读
- javascript - Cordova 音乐控制插件,如何使其工作?
- python - 使用 MultiIndex 删除 DataFrame 中的对称对
- git - 如何将一个 repo 移动到另一个 repo 文件夹并保留 git 历史记录?
- sql - 如何计算每个产品每天的库存给定天数在 PostgreSQL 之间缺失?
- c# - Identity Server 4 向用户添加自定义声明
- xml - 在 Snowflake 中解析嵌套的 XML
- python - Matplotlib 标签更改灰色阴影
- angular - ngrx 中的 StoreModule.forRoot 引发角度错误
- vba - VBA 宏报告 PowerPoint 幻灯片上的链接
- sql - 如何使用 XMLQuery 更新 clob Oracle 中的 XML 属性