【问题标题】:Write a large array to a file using node使用节点将大数组写入文件
【发布时间】:2020-05-18 18:30:29
【问题描述】:

我正在尝试将 csv 文件转换为数组中的对象并将其写入新文件。

我已经使用 csv-parser 转换了数据,但是在将数组写入新文件和访问数组中的数据时遇到问题。

这是我转换 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]......

有人知道我做错了什么吗?并提前感谢您的任何建议。

【问题讨论】:

    标签: javascript node.js json csv


    【解决方案1】:

    [object Object],[object Object],...[object Object] 也是来自realtorArray.toString() 的正确结果,使用String(realtorArray) 会得到相同的结果。

    JSON.stringify(realtorArray) 会将realtorArray 转换为等效的 JSON。所以...

    writeStream.write(JSON.stringify(realtorArray));
    

    应该将您的数据写入文件。

    【讨论】:

    • 这就是我第一次尝试使用但失败了。我一定错过了什么。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2019-02-07
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多