0

我编写了一个小 Node.js 脚本来从一个网站上抓取数据,我在该网站上迭代页面以提取结构化数据。

我为每一页提取的数据是对象数组的一种形式。

我想我可以使用fs.createWriteStream()方法来创建一个可写流,我可以在每次提取页面后增量写入数据。

显然,您只能将 String 或 Buffer 写入流,所以我正在做这样的事情:

output.write(JSON.stringify(operations, null, 2));

但最后,一旦我关闭流,JSON 格式错误,因为显然我只是一个接一个地附加每个页面的每个数组,结果如下所示:

[
    { ... },  /* data for page 1 */
    { ... }
][ /* => here is the problem */
    { ... },  /* data for page 2 */
    { ... }
]

我怎样才能继续将数组实际附加到输出中而不是链接它们?它甚至可以吗?

4

1 回答 1

2

你的选择是...

  1. 将完整的数组保存在内存中,并在处理完所有页面后仅在最后写入 json 文件。
  2. 单独编写每个对象,并手动处理方括号和逗号。

像这样的东西...

//start processing
output.write('[');
//loop through your pages, however you're doing that
while (more_data_to_read()) {
    //create "operation" object
    var operation = get_operation_object();
    output.write(JSON.stringify(operation, null, 2));
    if (!is_last_page()) {
        //write out comma to separate operation objects within array
        output.write(',');
    }
}
//all done, close the json array
output.write(']');

这将创建格式良好的 json。

就个人而言,我会选择#1,因为这似乎是更“正确”的方式。如果您担心数组使用太多内存,那么 json 可能不是数据文件的最佳选择。它不是特别适合非常大的数据集。

在上面的代码示例中,如果进程在中途被中断,那么您将拥有一个无效的 json 文件,因此逐步编写实际上不会使应用程序更具容错性。

于 2018-01-30T06:23:18.527 回答