我正在尝试通过 JSONStream.parse() 通过管道传输输入流(从巨大的 GeoJSON 文件创建)以将流分解为对象,然后通过 event-stream.map() 以允许我转换对象,然后通过 JSONStream .stringify() 创建一个字符串,最后创建一个可写的输出流。随着进程的运行,我可以看到节点的内存占用量继续增长,直到最终耗尽堆。这是重现问题的最简单的脚本 (test.js):
const fs = require("fs")
const es = require("event-stream")
const js = require("JSONStream")
out = fs.createWriteStream("/dev/null")
process.stdin
.pipe(js.parse("features.*"))
.pipe(es.map( function(data, cb) {
cb(null, data);
return;
} ))
.pipe(js.stringify("{\n\"type\": \"FeatureCollection\", \"features\": [\n\t", ",\n\t", "\n]\n}"))
.pipe(out)
一个小 bash 脚本(barf.sh)将无尽的 JSON 流注入节点的 process.stdin 中,这将导致节点的堆逐渐增长:
#!/bin/bash
echo '{"type":"FeatureCollection","features":['
while :
do
echo '{"type":"Feature","properties":{"name":"A Street"}, "geometry":{"type":"LineString"} },'
done
通过这样运行它:
barf.sh | node test.js
有几种奇怪的方法可以回避这个问题:
- 删除 fs.createWriteStream() 并将最后一个管道阶段从“.pipe(out)”更改为“.pipe(process.stdout)”,然后将管道节点的 stdout 更改为 /dev/null
- 将异步 es.map() 更改为同步 es.mapSync()
前面两个操作中的任何一个都将允许脚本永远运行,节点的内存占用量较低且不变。我在运行 Ubuntu 16.04、具有 8GB RAM 的八核机器上使用 Node v6.3.1、event-stream v3.3.4 和 JSONStream 1.1.4。
我希望有人能帮助我纠正我确信是我的明显错误。