user3647026
user3647026

Reputation: 43

How to know type of value of given key in redis in node js

I am doing a small project using redis and node js - redis client 'node_redis'. The problem is that, to get the key's value there are different get function like for string and integer type there is client.get, for array type there is client.lrange() etc. So how to identify what function to use to get the value if the desired value type is not known, is there a way to identify the value type.

Upvotes: 1

Views: 2407

Answers (2)

Matt
Matt

Reputation: 74670

Use the TYPE command.

2022 redis v4 - ES with await:

import { createClient } from 'redis'

async function go(){
  const client = createClient()
  client.on('error', console.error)
  await client.connect()

  const value = await client.TYPE('key')
}

redis v3 Promises:

const Promise = require('bluebird')
const redis = Promise.promisifyAll(require('redis'))
const client = redis.createClient()
client.on("error", err => console.log("Error " + err))

client.typeAsync('foo').then(res => {
  console.log('type: "%s"', res)
})
.finally(()=> {
  client.quit()
})

redis v3 callbacks:

const redis = require('redis')
const client = redis.createClient()
client.on("error", err => console.log("Error: %s", err))

client.type('foo', (err, res) =>{
  if (err) return console.log('Error: %s', err)
  console.log('type: "%s"', res)
  client.quit()
})

Upvotes: 5

Itamar Haber
Itamar Haber

Reputation: 49942

Usually your application should know in advance the type of value that it is accessing using a given key name. That said, there's the Redis TYPE that you can use for inspecting a given key's type.

Upvotes: 0

Related Questions