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

Jér*_*nge 12 javascript unzip text-files

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

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

小智 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();
Run Code Online (Sandbox Code Playgroud)

如果你看这里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)
Run Code Online (Sandbox Code Playgroud)

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

问题类似于 在Node.js跨平台下载和解压缩文件的最简单方法?

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