Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 515
Joshua Avatar asked Dec 11 '12 16:12

Joshua


People also ask

How do you decode a binary buffer to an image in node JS?

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.

Which node JS module should you use when you need to decode raw data into strings?

The String Decoder module provides a way of decoding Buffer objects into strings.

How to decode Base 64 in Node js?

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 is a buffer in Javascript?

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.


1 Answers

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.

like image 148
Esailija Avatar answered Sep 27 '22 20:09

Esailija