Rewriting a webapp so that it can run in both Node or Deno2, I get stuck on the following. The function has to read a base64 encoded gzip buffer containing a JSON string. This is the node implementation:
import zlib from 'node:zlib';
function from_base64_gzip(str){
let buff = Buffer.from(str, 'base64');
let json = zlib.unzipSync(buff).toString('utf-8');
return JSON.parse(json);
}
However deno2 does not have the Buffer
object, and atob()
only seems to work for strings and not for binary data.
Is there an elegant way to rewrite this such that it will run both in node and deno (preferably without extra npm deps)?
2
Answers
The answer was given in the comments: we can import the node buffer API as documented:
Note that
Buffer
is not the default export, hence we have to useimport { Buffer }
instead ofimport Buffer
, which is why I initially thought it did not work.A method that works in Deno, Node and the browser would be to use the
decodeBase64
function fromjsr:@std/encoding
, andtoBytes
fromjsr:@std/streams/unstable-to-bytes
. With these two dependencies, and the globalDecompressionStream
, one can construct the below function.The only difference between the output of these two functions is that this one is asynchronous and yours in synchronous.