javascriptnode.jses6-modulesdeno

How to port Buffer.from() to deno2


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)?


Solution

  • The answer was given in the comments: we can import the node buffer API as documented:

    import { Buffer } from "node:buffer";
    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);
    }
    

    Note that Buffer is not the default export, hence we have to use import { Buffer } instead of import Buffer, which is why I initially thought it did not work.