nodejs怎么存取2进制数据到数据库?

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

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 }
<Buffer 4a f5 ed 74>
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

以上就是nodejs怎么存取2进制数据到数据库?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Node.js答疑