Node.js – detect_buffers Property in Redis


Node.js Redis offers certain properties which can be used as per your usecase. One such property is detect_buffers.

  • If this property is set to True, then the replies that are sent to the callbacks are sent as buffers.

  • This option lets you switch between the buffer and strings based upon this single command basis.

  • This property does not work with pub-sub mode.

Syntax

detectBuffers: true

Example 1

Create a file with the name "detectBuffers.js" and copy the following code. After creating the file, use the command "node detectBuffers.js" to run this code, as shown in the example below:

// detect_buffers Property Demo Example

// Importing the redis module
const redis = require("redis");

// Creating redis client with detect_buffers property set as true
const client = redis.createClient({ detect_buffers: true });

// Setting key-value pair
client.set("foo_rand000000000000", "OK");

// Retrieving value based upon buffer key
client.get("foo_rand000000000000", function(err, reply) {
   console.log(reply.toString());
});

// Buffer will be returned since original key is specified as buffer
client.get(new Buffer("foo_rand000000000000"), function(err, reply) { 
   console.log(reply);
});

Output

It will produce the following output −

OK
<Buffer 4f 4b>

Example 2

Let's take another example

// detect_buffers Property Demo Example

// Importing the redis module
const redis = require("redis");

// Creating redis client with detect_buffers property set as true
const client = redis.createClient({ detect_buffers: true });

// Setting key-value pair
client.set("Hello", "TutorialsPoint");

// Buffer will be returned
client.get(new Buffer("Hello"), function(err, reply) { 
   console.log(reply);
});

Output

<Buffer 54 75 74 6f 72 69 61 6c 73 50 6f 69 6e 74>

Updated on: 24-Nov-2021

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements