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
...
from(data); //or Buffer. from(data, 'binary') let imgData = new Blob(binary. buffer, { type: 'application/octet-binary' }); let link = URL. createObjectURL(imgData); let img = new Image(); img.
The String Decoder module provides a way of decoding Buffer objects into strings.
Base64 Decoding All you need to do is create a buffer from the Base64 encoding string by using base64 as the second parameter to Buffer. from() and then decode it to the UTF-8 string by using the toString() method.
What Are Buffers? The Buffer class in Node. js is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With