mysql 二进制 nodejs_nodejs怎么存取2进制数据到数据库?

nodejs可以通过nodejs-redis模块来操作redis数据库,使用redis.createClient()连接redis数据库,可以直接将二进制数据存入数据库。通过redis-cli读取。

ba4be3201097ff6cca63bcbf2de70dfb.png

nodejs redis 读写二进制数据

通过nodejs-redis模块我们可以很方便的操作redis,npm上的说明如下:This is a complete Redis client for node.js. It supports all Redis commands and focuses on performance.

redis是支持二进制数据的,通过nodejs写入二进制数据的代码如下:'use strict';

var redis = require("redis")

var client = redis.createClient();

var array = new Uint8Array(4);

array[0] = parseInt(Math.random()*0xFF);

array[1] = parseInt(Math.random()*0xFF);

array[2] = parseInt(Math.random()*0xFF);

array[3] = parseInt(Math.random()*0xFF);

console.log(array);

var buf = new Buffer(array);

console.log(buf);

client.set('test', buf, function(err, response) {

console.log('set OK, response:' + response);

});

上面代码的输出以及通过redis-cli读取的结果分别如下:$ node redisWithBinary.js

Uint8Array { '0': 74, '1': 245, '2': 237, '3': 116 }

set OK, response:OK

$ redis-cli get test

"J\xf5\xedt"

注意: redis-cli对于可打印内容和不可打印的字符分别使用字符和十六进制转义进行显示。

使用nodejs读取redis中的二进制数据,代码如下:client.get('test', function(err, res) {

console.log('res typeof:'+ typeof res);

console.log('res:' + res);

var buf = new Buffer(res);

console.log(buf);

});

输出结果:res typeof:string

res:J��t

res.charCodeAt(i): 0x4a

res.charCodeAt(i): 0xfffd

res.charCodeAt(i): 0xfffd

res.charCodeAt(i): 0x74

问题出现了:

1. 通过get读取出来的数据类型是string,并不是raw data

2. 将该string转为Buffer后,对于不认识的字符直接转换为ef bf bd,通过测试,在设置了encoding格式为ascii和binary后,输出都是,同样是转为了固定的一个值fd

对于res字符串中的内容,我们可以通过下述代码进行仔细确认:client.get('test', function(err, res) {

console.log('res typeof:'+ typeof res);

console.log('res:' + res);

for (var i =0; i < res.length; i++) {

console.log('res.charCodeAt(i): 0x'+res.charCodeAt(i).toString(16));

}

});

输出结果:res typeof:string

res:J��t

res.charCodeAt(i): 0x4a

res.charCodeAt(i): 0xfffd

res.charCodeAt(i): 0xfffd

res.charCodeAt(i): 0x74

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值