Cle*_*016 1 javascript json fs node.js node-streams
我编写了一个 Node.js 脚本来从网站上抓取数据,我在该网站上迭代页面以提取结构化数据。
我为每个页面提取的数据是对象数组的一种形式。
我认为我可以使用fs.createWriteStream()方法创建一个可写流,在每个页面提取后我可以在该流上增量写入数据。
显然,你只能将字符串或缓冲区写入流,所以我正在做这样的事情:
output.write(JSON.stringify(operations, null, 2));
Run Code Online (Sandbox Code Playgroud)
但最后,一旦我关闭流,JSON 就会格式错误,因为显然我只是一个接一个地附加每个页面的每个数组,结果看起来像这样:
[
{ ... }, /* data for page 1 */
{ ... }
][ /* => here is the problem */
{ ... }, /* data for page 2 */
{ ... }
]
Run Code Online (Sandbox Code Playgroud)
我怎样才能将数组实际附加到输出中而不是链接它们?它甚至可行吗?
你的选择是...
像这样的东西...
//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(']');
Run Code Online (Sandbox Code Playgroud)
这将创建格式良好的 json。
就我个人而言,我会选择#1,因为这似乎是更“正确”的方法。如果您担心数组使用太多内存,那么 json 可能不是数据文件的最佳选择。它不太适合非常大的数据集。
在上面的代码示例中,如果进程中途中断,那么您将得到一个无效的 json 文件,因此渐进式写入实际上不会使应用程序更具容错性。
| 归档时间: |
|
| 查看次数: |
8487 次 |
| 最近记录: |