Node.JS reading BLOB from mysql

北城余情 提交于 2019-12-20 19:48:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!