Friday 15 May 2015

node.js - Binary data stored in MySQL is getting corrupted with Node -



node.js - Binary data stored in MySQL is getting corrupted with Node -

i'm using node-mysql2 , storing string-encoded binary info in mysql. column has type of binary(16). info stored in mysql beingness corrupted, example:

nodejs output: 47 23 43 14 ed 86 14 dc 12 f3 b8 6c dc 31 fb fa mysql hex() : 47 23 43 14 c3 advertisement c2 86 14 c3 9c 12 c3 b3 c2 b8

code:

var binarystring = randombinarystring(); db.sqlquery("insert test(binarystring) values(" + db.escape(binarystring) + ")"); console.log(new buffer(binarystring, 'binary').tostring('hex')); function randombinarystring(){ var str = ""; for(var = 0; < 16; i++){ str += string.fromcharcode(math.floor(math.random()*256)); } homecoming str; }

how should string encodes binary info (each character beingness byte) stored in mysql using node-mysql2?

you're not inserting raw binary string utf-8 encoded string. in utf-8, codepoints after 127 encoded using multiple bytes. 5th byte ed (237) encoded using 2 bytes.

buffer(string.fromcharcode(0xed)) produces : <buffer c3 ad>

sending random string buffer binary encoding should prepare problem. node-mysql convert buffer hex string when inserting.

db.query('insert test values (?)', [ buffer(randomstring(), 'binary') ]);

also, crypto module has randombytes method generates n random bytes.

db.query('insert test values (?)', [crypto.randombytes(16)]);

mysql node.js node-mysql

No comments:

Post a Comment