node.js - 缓冲区到字符串格式错误的编码(本机 ZLIB 压缩 - Node.js)
问题描述
您好,我正在将 JSON 通过 zlib 进行压缩,将其作为缓冲区存储在平面文件数据库中,然后读取并发送出去。
除了我的问题是数据是各种疯狂的字符。我试过 .toString() 我试过 Node 的官方 StringDecoder。我已经尝试了很多东西,但是当我实际上需要输出的最终 JSON 时,除了 .toJSON 可读作为 JSON 缓冲区之外,我似乎无法以任何格式获得它。
想法?
写入平面文件数据库
export const writeCollection = (index, timespan, data) => {
zlib.gzip(JSON.stringify(data), (err, result) => {
if (err) {
console.log({ err });
} else {
const keyName = dbCollections.gzip[index].add({
result
});
collectionKeys.gzip[index] = keyName;
writeLogging(timespan, keyName, index, "gzip");
}
});
zlib.brotliCompress(JSON.stringify(data), (err, result) => {
if (err) {
console.log({ err });
} else {
const keyName = dbCollections.brotli[index].add({
result
});
collectionKeys.brotli[index] = keyName;
writeLogging(timespan, keyName, index, "brotli");
}
});
};
从平面文件数据库中读取
export const readCollection = (index, encoding) => {
const encodedRead = encoding.includes("br")
? dbCollections.brotli[index].all()
: dbCollections.gzip[index].all();
return encodedRead[0].result;
};
尝试转换为 JSON
export const testGetQuakeData = (req, res) => {
const encoding = req.headers["accept-encoding"];
try {
const data = readCollection(0, encoding);
console.log(data)
const json = decoder.write(Buffer.from(data));
console.log(json)
// res.set({
// 'Content-Type': 'application/json',
// 'Content-Encoding': encoding.includes('br') ? 'br' : "gzip",
// })
res.send(json)
} catch (err) {
console.log({ err });
res.status(500).send(err);
}
};
解决方案
忘记用 ZLIB 解压了!
export const testGetQuakeData = (req, res) => {
const encoding = req.headers["accept-encoding"];
try {
const data = readCollection(0, encoding);
encoding.includes("br")
? zlib.brotliDecompress(data, (err, result) => {
err ? res.status(500).send(err) : res.send(decoder.write(result));
})
: zlib.unzip(data, (err, result) => {
err ? res.status(500).send(err) : res.send(decoder.write(result));
});
} catch (err) {
console.log({ err });
res.status(500).send(err);
}
};
这是未来的产品功能!
export const testGetCompressedQuakeData = (req, res) => {
const encoding = req.headers["accept-encoding"];
try {
const data = readCollection(0, encoding);
encoding.includes("br")
? res.writeHead(200, {
"Content-Type": "application/json",
"Content-Encoding": "br",
"Content-Length": data.length,
})
: res.writeHead(200, {
"Content-Type": "application/json",
"Content-Encoding": "gzip",
"Content-Length": data.length,
})
res.end(data)
} catch (err) {
console.log({ err });
res.status(500).send(err);
}
};
内容长度 6319 (Brotli) vs 63148 (JSON) Brotli 压缩获胜!
推荐阅读
- sql - 打印两个表中的所有字段,并使用 ORACLE CASE 语句根据列将某些列值设置为空
- logging - 使用 PutSQL 处理器登录 NiFi 时出错
- python - 使用线程/多进程从 API 加载时如何计算时间并设置时间限制?
- python - 如何在 django 类基础视图中注册后自动登录
- laravel - 如何在laravel中将值数组转换为字符串?
- python - 将数据从 JSON 输出到 Telegram
- javascript - 是否有必要在字符串数组和对象扩展运算符之间拆分 mapState?
- jquery - jQuery Modal - 在 Ajax 成功时从一个模态重定向到另一个模态
- wordpress - 竞争增值税验证器结帐 WooCommerce
- java - 为什么android的checkbox这么慢?