Gzip 的 JavaScript 实现 [英] JavaScript implementation of Gzip
问题描述
我正在编写一个 Web 应用程序,它需要通过 AJAX 将 JSON 数据存储在一个小的、固定大小的服务器端缓存中(想想:开放社交配额).我无法控制服务器.
I'm writing a Web application that needs to store JSON data in a small, fixed-size server-side cache via AJAX (think: Opensocial quotas). I do not have control over the server.
我需要减少存储数据的大小以保持在服务器端配额内,并希望能够在将字符串化的 JSON 发送到服务器之前在浏览器中对其进行 gzip.
I need to reduce the size of the stored data to stay within a server-side quota, and was hoping to be able to gzip the stringified JSON in the browser before sending it up to the server.
然而,我在 Gzip 的 JavaScript 实现方面找不到太多的东西.关于如何在发送数据之前在客户端压缩数据的任何建议?
However, I cannot find much in the way of JavaScript implementations of Gzip. Any suggestions for how I can compress the data on the client side before sending it up?
推荐答案
Edit 在 http://pieroxy.net/blog/pages/lz-string/index.html(感谢 pieroxy 在评论中).
Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments).
我不知道任何 gzip 实现,但是 jsolait 库(该站点似乎已经消失)具有 LZW 压缩/解压功能.该代码包含在 LGPL 下.
I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL.
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
这篇关于Gzip 的 JavaScript 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!