我正在尝试将csv文件转换为数组中的对象,并将其写入新文件。
我已经用csv解析器转换了数据,但是我很难将数组写入一个新文件并访问数组中的数据。
这是我转换csv文件的代码:
const csv = require('csv-parser');
const fs = require('fs');
const readStream = fs.createReadStream('agents.csv');
const writeStream = fs.createWriteStream('agent_data.txt');
let realtorArray = [];
readStream.pipe(csv())
.on('data', (data) => {
realtorArray.push(data);
})
.on('end', () => {
//I've tried writing the array to a file in three ways
//The first way was JSON.stringify() but that failed due to the file size I think.
//Second I tried toString-ing the array as below...
writeStream.write(realtorArray.toString());
//Third way was creating a buffer...
let buf = Buffer.from(String(realtorArray));
writeStream.write(buf);
console.log('CSV file successfully processed');
writeStream.end();
});转换后的CSV数据如下所示:
[
{
'License Type': 'BRK',
'License Number': '12345',
'Full Name': 'John Doe',
'License Status': '20',
'Original License Date': '1234567',
'License Expiration Date': '12345678',
'Education Status': '0',
'Agency Identifier': '5431424'
}, {
'License Type': 'BRK',
'License Number': '4312241',
'Full Name': 'Jane Doe',
'License Status': '20',
'Original License Date': '5433234',
'License Expiration Date': '12345435',
'Education Status': '0',
'Agency Identifier': '11222234444'
},
......
],然后,当我以各种方式写入文件时,我尝试了.
当我使用.toString()时,数据如下所示:
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]...............当我创建缓冲区时,数据如下所示:
<Buffer 5b 6f 62 6a 65 63 74 20 4f 62 6a 65 63 74 5d 2c 5b 6f 62 6a 65 63 74 20 4f 62 6a 65 63 74 5d 2c 5b 6f 62 6a 65 63 74 20 4f 62 6a 65 63 74 5d 2c 5b 6f ... >当我试着读数据时..。
如果我在写入和使用toString()时缓冲或JSON.stringify(data)数据,则读取它:
{
"type": "Buffer",
"data": [91,111,98,106,101,99,116,32,79,98,106,101,99,........]
}如果我在写时.toString()它,并尝试阅读它,它看起来与上面或类似的。
[object Object],[object Object],[object Object],[object Object]......有人知道我做错了什么吗?谢谢你事先给我的建议。
发布于 2020-02-03 00:39:40
[object Object],[object Object],...[object Object]也是来自realtorArray.toString()的正确结果,使用String(realtorArray)也会给出相同的结果。
JSON.stringify(realtorArray)将把realtorArray转换成它的JSON等价物。所以..。
writeStream.write(JSON.stringify(realtorArray));应该将数据写入文件。
https://stackoverflow.com/questions/60031808
复制相似问题