How to decode "binary" encoded string into raw binary Buffer?

27,893
const buffer = new Buffer(binaryString, "binary");

Tested with:

$ node
> var binaryString = "\xff\xfa\xc3\x4e";
> var buffer = new Buffer(binaryString, "binary");
> console.log(buffer);
<Buffer ff fa c3 4e>

Update: since v10.0.0 - Use Buffer.from(string[, encoding]) instead.

Share:
27,893
Joshua
Author by

Joshua

Updated on August 04, 2021

Comments

  • Joshua
    Joshua almost 3 years

    The NodeJS docs stress that the binary string encoding is heavily discouraged since it will be dropped at some point in the future.

    However, I'm trying to generate image thumbnails with the node-imagemagick module, which can only output binary encoded strings.

    My end goal is to submit the generated thumbnail as a BLOB into a SQLite3 database (I'm using node-sqlite3), so I figured I need the thumbnail as a binary Buffer object.

    How do I directly decode the binary encoded output from node-imagemagick into a raw binary Buffer (not just a Buffer that contains a binary encoded string)? I'm not keen on using base64...

  • huysentruitw
    huysentruitw over 10 years
    You didn't misinterpreted the docs. They clearly state that "binary" encoding will get removed! I'm also running against the same problem while capturing output from ImageMagick to store into MongoDB. "binary" is the only encoding that seems to work to get STDOUT in the database correctly. So what is the alternative?
  • Esailija
    Esailija over 10 years
    @WouterHuysentruit raise an issue with the library author on github to update their module to use buffers... it will surely get resolved before "binary" gets removed from node?