Created
August 29, 2022 20:10
-
-
Save brandonros/b085a00d8470dd1c83f94d42fd192174 to your computer and use it in GitHub Desktop.
JSONBrotliAdapter for lowdb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import zlib from 'zlib' | |
| import fs from 'fs' | |
| class JSONBrotliAdapter { | |
| constructor(filename) { | |
| this.filename = filename | |
| } | |
| async read() { | |
| let compressedData = null | |
| try { | |
| compressedData = await fs.promises.readFile(this.filename) | |
| } catch (err) { | |
| if (err.code === 'ENOENT') { | |
| return null | |
| } | |
| throw err | |
| } | |
| const uncompressedData = await new Promise((resolve, reject) => { | |
| zlib.brotliDecompress(compressedData, (err, result) => { | |
| if (err) { | |
| return reject(err) | |
| } | |
| resolve(result) | |
| }) | |
| }) | |
| return JSON.parse(uncompressedData.toString()) | |
| } | |
| async write(data) { | |
| const uncompressedData = Buffer.from(JSON.stringify(data)) | |
| const compressedData = await new Promise((resolve, reject) => { | |
| zlib.brotliCompress(uncompressedData, (err, result) => { | |
| if (err) { | |
| return reject(err) | |
| } | |
| resolve(result) | |
| }) | |
| }) | |
| await fs.promises.writeFile(this.filename, compressedData) | |
| } | |
| } | |
| export default JSONBrotliAdapter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment