Node.JS reading blob from mysql

I am using the Node.JS module node-mysql. One column is of type BLOB and wants to read it, and, if possible, base64 encodes it. I could not find anything about how to do this.

Any ideas?

+7
source share
2 answers

Try the following snippet:

var buffer = new Buffer( blob ); var bufferBase64 = buffer.toString('base64'); 

If your blob is binary, use the following instead:

 var buffer = new Buffer( blob, 'binary' ); var bufferBase64 = buffer.toString('base64'); 

You can also simplify this in one line:

 var bufferBase64 = new Buffer( blob, 'binary' ).toString('base64'); 
+15
source

Note: mysql-node automatically converts Blob objects to JavaScript buffer objects.
The above answer refers to base64 encoding.

For me, the easiest way to simply read it as a string in node was: myObject.myBlobAttr.toString('utf-8')


As of January 28, 2015,
From the Felix mysql-node page :

Type of casting

For your convenience, this driver will use mysql types for native JavaScript types by default. The following mappings are available:

...

Buffer

TINYBLOB
MEDIUMBLOB
LONGBLOB
Blob
Binary
VARBINARY
BIT (last byte will be filled 0 bits as needed)


Edit Alternative for UTF-8 (?)

String.fromCharCode.apply(null, new Uint16Array(myObject.myBlobAttr));

+9
source

All Articles