问题
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?
回答1:
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');
    回答2:
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));
来源:https://stackoverflow.com/questions/9042327/node-js-reading-blob-from-mysql