exists
1. 基本語法
exist(key
, callback
)
key
, callback
) 確定key
名稱是否存在資料,存在則回傳1,不存在則回傳0。
2. 範例
(1) 確認key
名稱是否已被使用
key
名稱是否已被使用client.set('foo', 'bar');
client.exists('foo',redis.print);
client.exists('woo',redis.print);
Reply: 1
Reply: 0
(2) 情境:key
值存在則讀取(get),不存在則新增(set)
key
值存在則讀取(get),不存在則新增(set)透過callback
取得回傳值,並置入條件句進行判斷。以下程式碼重複執行兩次後,所得到的結果並不同:第一次key
值不存在,因此新增該key
名稱與資料;第二次由於該key
值已存在,因此回傳資料內容。
const mykey = 'new_foo';
client.exists(mykey, (err, isExist)=>{
if (isExist){
console.log('[key exist]');
client.get(mykey, redis.print);
}else{
console.log('[new key]');
client.set(mykey, 'new_bar', redis.print);
}
});
[new key]
Reply: OK
----------
[key exist]
Reply: new_bar
Last updated
Was this helpful?