Cloudflare Workers: Iterate / Loop Over KV Namespace
Loop / iterate over KV keys in Cloudflare workers. In this example, I limited the output for the list
request to 2 on purpose to check if everything works as expected.
async function listAll() {
// list all keys from a given NAMESPACE,
// in this example the output is limited to two on purpose
// to make it paginate. The default is 1000
let entries = await NAMESPACE.list({ limit: 2, type: 'json' })
// get cursor, if returned
let cursor = entries.cursor
let loop = []
// get entries from first call above
let output = { ...entries.keys }
// as long as `entries.list_complete` is false, loop over the next block
while (!entries.list_complete) {
let next_value = await NAMESPACE.list({ cursor: cursor, limit: 2, type: 'json' })
// update `entries.list_complete` to break the loop
// as soon as we've got all keys
entries.list_complete = next_value.list_complete
// update cursor for the next call
cursor = next_value.cursor
loop.push(...next_value.keys)
}
// merge keys from very first output with all the subsequent keys
// from paginated calls
output = { ...output, ...loop }
return output
}