Redis saving strings as buffers on some OSs, not o

2019-05-09 10:53发布

I'm using Redis 2.2.11 with Node on Ubuntu 11.10, and I'm saving a string but it's being returned as a Buffer.

    id = 1234;
    console.log('data', data);
    client.hmset("user:" + id, "name", data['name'] );
    client.hmget('user:' + id, "name", function(err, d) {
        console.log('data retrieved', d);
    });

This produces the following at the console:

data { name: 'RealServer' }
data retrieved [ <Buffer 41 6e 6e 61 52 65 61 6c 53 65 72 76 65 72> ]

Why is it going in as a string, and coming out as a Buffer? The Buffer makes debugging very difficult!

On my local setup (MacOS 10.6 with Redis 2.2.14) the data retrieved prints as a string, just fine. I'd like to find a solution that continues to work on both systems.

UPDATE: It also works fine without an encoding specified on CentOS 5.7. Is this something specific to Ubuntu? Is there a system-wide fix?

2条回答
戒情不戒烟
2楼-- · 2019-05-09 11:48

See: http://nodejs.org/docs/v0.3.1/api/buffers.html

Pure Javascript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.

Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.

The Buffer object is global.

Converting between Buffers and JavaScript string objects requires an explicit encoding method.

Because you've not specified an encoding, it displays as raw data by default. You can use buffer.toString to produce a standard JS string.

查看更多
混吃等死
3楼-- · 2019-05-09 11:53

Since you haven't specified an encoding it doesn't know what encoding to use while printing it out. Use the toString function with the encoding as a paramater to properly log it.

client.hmget('user:' + id, "name", function(err, d) {
    console.log('data retrieved', d.toString('utf8'));
});
查看更多
登录 后发表回答