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

binary, buffer, encoding, imagemagick, node.js

Solution

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.

Problem

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`...

Original source