How to List Values in Deno KV: Syntax and Example
To list values in
Deno KV, use the kv.list() method with an optional key prefix or range. This returns an async iterator over key-value pairs, which you can loop through with for await to access stored values.Syntax
The kv.list() method retrieves entries from the Deno KV store. You can pass a key prefix or a range to filter keys.
- kv.list(prefixOrRange): Returns an async iterator of entries matching the prefix or range.
- prefixOrRange: Optional. A key prefix array or a range object to specify which keys to list.
- Each entry is an object with
keyandvalueproperties.
typescript
const iterator = kv.list(['user']); for await (const entry of iterator) { console.log(entry.key, entry.value); }
Example
This example shows how to store some values in Deno KV and then list all values with a common prefix.
typescript
import { openKv } from "https://deno.land/x/kv/mod.ts"; const kv = await openKv(); // Store some user data await kv.set(['user', '1'], { name: 'Alice', age: 30 }); await kv.set(['user', '2'], { name: 'Bob', age: 25 }); await kv.set(['user', '3'], { name: 'Carol', age: 28 }); // List all users console.log('Listing users:'); for await (const entry of kv.list(['user'])) { console.log(entry.key, entry.value); }
Output
Listing users:
["user", "1"] { name: 'Alice', age: 30 }
["user", "2"] { name: 'Bob', age: 25 }
["user", "3"] { name: 'Carol', age: 28 }
Common Pitfalls
1. Forgetting to use for await when iterating the async iterator will cause errors.
2. Using incorrect key prefixes or ranges can return no results.
3. Not awaiting kv.set() before listing may cause missing entries.
typescript
/* Wrong: missing await in for loop */ const iterator = kv.list(['user']); for (const entry of iterator) { console.log(entry.key, entry.value); // Error: iterator is async } /* Right: use for await */ for await (const entry of kv.list(['user'])) { console.log(entry.key, entry.value); }
Quick Reference
kv.list(prefix): List entries with keys starting with prefix.for await (const entry of kv.list(...)): Iterate async entries.entry.key: The key array of the entry.entry.value: The stored value.
Key Takeaways
Use kv.list() with a key prefix to get an async iterator of matching entries.
Always use for await to loop over the async iterator returned by kv.list().
Ensure you await kv.set() calls before listing to see all stored values.
Keys in Deno KV are arrays; use matching prefixes to filter listings.
Each entry from kv.list() has key and value properties to access.