node.jscompressionzliblzw

NodeJS Zlib support for LZW ("compress") algorithm?


I've got a Node/ExpressJS server whose client software only has access to the "compress" (LZW) algorithm for de/compression.

As far as I can tell the Node 12.X zlib library does not support LZW. There also don't appear to be any modules in npm that handle LZW in a fast, general way on content larger than a few hundred bytes.

Does anyone know of a way to efficiently and, ideally, natively use LZW on a Node server? Is something in Zlib compatible with LZW? My use case is for data up to a few tens of kilobytes.

Everything is in Docker, so I could install ncompress on the host and use child_process to call it directly, or something, but that seems convoluted.


Solution

  • You could do this without any external library. These are two LZW encode and decode functions.

    function en(c) { var x = "charCodeAt", b, e = {}, f = c.split(""), d = [], a = f[0], g = 256; for (b = 1; b < f.length; b++) c = f[b], null != e[a + c] ? a += c :(d.push(1 < a.length ? e[a] :ax),
    e[a + c] = g, g++, a = c); d.push(1 < a.length ? e[a] :ax);
    for (b = 0; b < d.length; b++) d[b] = String.fromCharCode(d[b]);
    return d.join(""); }

    function de(b) { var a, e = {}, d = b.split(""), c = f = d[0], g = [ c ], h = o = 256; for (b = 1; b < d.length; b++) a = d[b].charCodeAt(0), a = h > a ? d[b] :e[a] ? e[a] :f + c,
    g.push(a), c = a.charAt(0), e[o] = f + c, o++, f = a; return g.join(""); }

    Please note: These functions are for strings only. Source: https://gist.github.com/JavaScript-Packer/bbf68a4dc0e1fd102221