14

I'm using the Node.JS node-mysql module. One column has a BLOB type and want to read from it and if possible base64 encode it. I haven't been able to find anything on how to do this.

Any ideas?

2 Answers 2

26

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 that to one line:

var bufferBase64 = new Buffer( blob, 'binary' ).toString('base64');
Sign up to request clarification or add additional context in comments.

3 Comments

blob is undefined!
new Buffer is depreciated now - use Buffer.from()
@RozzA Buffer.from(blob,'binary').toString(); is that okay to convert Blob into string.
22

Of note: mysql-node automatically converts Blob objects into javascript Buffer objects.
The above answer addresses base64 encoding.

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


As of Jan 28, 2015,
From Felix's mysql-node page:

Type casting

For your convenience, this driver will cast mysql types into native JavaScript types by default. The following mappings exist:

...

Buffer

TINYBLOB
MEDIUMBLOB
LONGBLOB
BLOB
BINARY
VARBINARY
BIT (last byte will be filled with 0 bits as necessary)


Edit Alternate option for UTF-8 (?)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.