Deno で JSON を Compression Streams で gzip 圧縮して保存/読み込んで展開
Denoで、といいつつ Deno らしさはあまりないけど
それが Deno のいいところでもある…
このくらいのことが標準APIだけでできると、うれしい
code:ts
await ReadableStream.from(JSON.stringify(value))
.pipeThrough(new TextEncoderStream())
.pipeThrough(new CompressionStream("gzip"))
.pipeTo((await Deno.open("filename.gzip", { write: true, create: true })).writable);
てなわけで改良版
code:ts
await (new Response(JSON.stringify(value))).body!
.pipeThrough(new CompressionStream("gzip"))
.pipeTo((await Deno.open("filename.gzip", { write: true, create: true })).writable);
なんか突然 Response を持ち出してくるのがキモいけど文字列から ReadableStream を作るショートカットです。
読むほう
code:ts
let jsonStr = "";
for await (const chunk of (await Deno.open("filename.gzip")).readable.pipeThrough(new DecompressionStream("gzip")).pipeThrough(new TextDecoderStream())) { // ←この行長すぎる!!
jsonStr += chunk;
}
const value = JSON.parse(jsonStr);
ReadableStream(というか async iterator)を最後まで全部読む、みたいなメソッドや構文は無いので(それはそう、無限かもしれないからね……)書き込みのときのようにワンライナーでは書けなさそう。