获取压缩文本文件并在客户端浏览器中解压缩,在Javascript中可行吗?

时间:2013-02-06 11:23:08

标签: javascript text-files unzip

我正在开发一个包含Javascript的网页。此js使用存储在平面文件中的静态字符串数据(大约1-2 MB)。我可以用gzip或任何其他算法压缩它以减少传输负载。

是否可以使用Ajax获取此二进制文件并将其解压缩为客户端浏览器中的字符串(我可以稍后拆分)。如果是,我怎样才能实现这一目标?有没有人有代码示例?

3 个答案:

答案 0 :(得分:11)

另一个图书馆或网站就是这个,虽然它的例子很少,但它有一些可以看到的全面的测试用例。

https://github.com/imaya/zlib.js

以下是一些复杂的测试用例 https://github.com/imaya/zlib.js/blob/master/test/browser-test.js https://github.com/imaya/zlib.js/blob/master/test/browser-plain-test.js

代码示例看起来非常紧凑。只是这两行代码......

// compressed = Array.<number> or Uint8Array
var gunzip = new Zlib.Gunzip(compressed);
var plain = gunzip.decompress();

如果你看这里https://github.com/imaya/zlib.js/blob/master/bin/gunzip.min.js,你会看到他们有你需要包含的打包js文件。您可能需要在https://github.com/imaya/zlib.js/blob/master/bin中包含其他一个或两个。

在任何情况下,将这些文件放入您的页面,然后从服务器提供GUzzip对象预先解压缩的数据,然后它将按预期进行。

您需要下载数据并使用其他功能自行将其导入阵列。我不认为他们包含这种支持。

请尝试从https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data

下载这些示例
function load_binary_resource(url) {
  var req = new XMLHttpRequest();
  req.open('GET', url, false);
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null);
  if (req.status != 200) return '';
  return req.responseText;
}

// Each byte is now encoded in a 2 byte string character. Just AND it with 0xFF to get the actual byte and then feed that to GUnzip...
var filestream = load_binary_resource(url);
var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)

===================================== 还有Node.js

问题类似于 Simplest way to download and unzip files in Node.js cross-platform?

nodejs文档中有这个示例代码。我不知道它有多具体...... http://nodejs.org/api/zlib.html

答案 1 :(得分:3)

只需在Apache上启用Gzip压缩,一切都将自动完成。

可能你必须将字符串存储在.js文件中作为json并为js mime类型启用gzip。

答案 2 :(得分:1)

我记得我使用js-deflate用于带有大型数据库的off-linne JS应用程序(由于本地存储的限制而需要)并且工作得很好。这取决于js-base64