Redis HSTRLEN in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

The HSTRLEN command in Redis is used to get the length of the value of a field in a hash stored at key. In Node, it's primarily used when you need to check the size of a particular value of a field without retrieving the entire value.

Code Examples

Let's consider an example where we have a user profile stored in a Redis hash, and we want to know the length of the user's bio description without retrieving the complete data.

const redis = require('redis'); const client = redis.createClient(); client.hset('user:1000', 'bio', 'Software Engineer at XYZ co.', redis.print); client.hstrlen('user:1000', 'bio', function(err, len) { if (err) throw err; console.log(len); // Outputs: 28 });

In this example, we're setting the bio field for user with id 1000 as 'Software Engineer at XYZ co.' and then checking its length using hstrlen. The result would be 28 since that's the length of the string.

Best Practices

  • Use HSTRLEN only when you need the length of a large string value in a hash. Using HGET followed by length in JavaScript would be more efficient for small strings.
  • Error handling is important when working with asynchronous operations like Redis commands in Node. Always include error checks in your callback functions.

Common Mistakes

  • HSTRLEN returns 0 if the field or key does not exist. Make sure the key and field exists in the hash before calling HSTRLEN.
  • Remember that HSTRLEN will return the length of the string as stored by Redis, not the size in memory.


Q: What if the key or field does not exist in the hash? A: If the key or field does not exist, HSTRLEN returns 0.

Q: Does HSTRLEN count multi-byte characters correctly? A: Yes, HSTRLEN counts each character accurately regardless of whether they are single or multi-byte.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.