externalKeyValueStore
Index
Properties
externalreadonlybackend
externalreadonlyconfiguration
externalreadonlyid
externaloptionalreadonlyname
Accessors
externalstats
Backend-independent usage counters tracked for this key-value store (read / write / delete / list operations issued to the underlying storage backend). Counted per backend call.
Returns KeyValueStoreStats
Methods
external[asyncIterator]
Default async iterator for the key-value store, iterating over entries (key-value pairs). Allows using the store directly in a
for await...ofloop.Example usage:
const keyValueStore = await KeyValueStore.open();for await (const [key, value] of keyValueStore) {console.log(`${key}: ${value}`);}Returns AsyncGenerator<[string, T], void, undefined>
externaldrop
Removes the key-value store either from the Apify cloud storage or from the local directory, depending on the mode of operation.
Returns Promise<void>
externalentries
Returns key-value store entries (key-value pairs).
When awaited (
await store.entries()), returns all entries as a flat[key, value][]array. When used as an async iterable (for await...of), iterates over all entries across pages without loading everything into memory at once.Example usage:
const keyValueStore = await KeyValueStore.open();// Iterate over all entries (memory-efficient for large stores)for await (const [key, value] of keyValueStore.entries()) {console.log(`${key}: ${value}`);}// Or fetch all entries at onceconst allEntries = await keyValueStore.entries();console.log(allEntries);Parameters
externaloptionaloptions: KeyValueStoreIteratorOptions
Options for the iteration.
Returns AsyncIterable<[string, T], any, any> & Promise<[string, T][]>
externalforEachKey
Iterates over key-value store keys, yielding each in turn to an
iterateefunction. Each invocation ofiterateeis called with three arguments:(key, index, info), wherekeyis the record key,indexis a zero-based index of the key in the current iteration andinfois an object that contains a single propertysizeindicating size of the record in bytes.If the
iterateefunction returns a Promise then it is awaited before the next call. If it throws an error, the iteration is aborted and theforEachKeyfunction throws the error.Example usage
const keyValueStore = await KeyValueStore.open();await keyValueStore.forEachKey(async (key, index, info) => {console.log(`Key at ${index}: ${key} has size ${info.size}`);});Parameters
externaliteratee: KeyConsumer
A function that is called for every key in the key-value store.
externaloptionaloptions: KeyValueStoreIteratorOptions
All
forEachKey()parameters.
Returns Promise<void>
externalgetAutoSavedValue
Parameters
externalkey: string
externaloptionaldefaultValue: T
Returns Promise<T>
externalgetPublicUrl
Returns a file URL for the given key.
The URL is derived from the key, so it is also returned for a record that does not exist (yet) — including one written earlier in an uncommitted storage transaction. Returns
undefinedonly when the storage has no file URLs at all (e.g. the in-memory storage).Parameters
externalkey: string
The key of the record to generate the public URL for.
Returns Promise<undefined | string>
externalgetRecord
Reads a record from the key-value store without parsing the value.
Use this when you need the raw bytes and the content type — for example, to run your own parser (
simdjson, a custom XML library, etc.) or to forward the bytes verbatim.There is no symmetric
setRecordmethod, because KeyValueStore.setValue already passes aBuffer(orstring/Stream) through unchanged when an explicitcontentTypeis provided. To write pre-serialized bytes, callsetValue(key, buffer, { contentType: 'application/json; charset=utf-8' }).Returns
nullif the record does not exist.Example usage:
const store = await KeyValueStore.open();const record = await store.getRecord('huge.json');if (record) {const data = simdjson.parse(record.value);}Parameters
externalkey: string
Unique key of the record. It can be at most 256 characters long and only consist of the following characters:
a-z,A-Z,0-9and!-_.'()
Returns Promise<null | KeyValueStoreRawRecord>
externalgetValue
Gets a value from the key-value store.
The function returns a
Promisethat resolves to the record value, whose JavaScript type depends on the MIME content type of the record. Records with theapplication/jsoncontent type are automatically parsed and returned as a JavaScript object. Similarly, records withtext/plaincontent types are returned as a string. For all other content types, the value is returned as a rawBufferinstance.If the record does not exist, the function resolves to
null.To save or delete a value in the key-value store, use the KeyValueStore.setValue function.
Example usage:
const store = await KeyValueStore.open();const buffer = await store.getValue('screenshot1.png');Parameters
externalkey: string
Unique key of the record. It can be at most 256 characters long and only consist of the following characters:
a-z,A-Z,0-9and!-_.'()
Returns Promise<null | T>
Returns a promise that resolves to an object, string or
Buffer, depending on the MIME content type of the record.
externalkeys
Returns key-value store keys.
When awaited (
await store.keys()), returns all keys as a flatstring[]array. When used as an async iterable (for await...of), iterates over all keys across pages without loading everything into memory at once.Example usage:
const keyValueStore = await KeyValueStore.open();// Iterate over all keys (memory-efficient for large stores)for await (const key of keyValueStore.keys()) {console.log(key);}// Or fetch all keys at onceconst allKeys = await keyValueStore.keys();console.log(allKeys);Parameters
externaloptionaloptions: KeyValueStoreIteratorOptions
Options for the iteration.
Returns AsyncIterable<string, any, any> & Promise<string[]>
externalpurge
Removes all records from the store but keeps the store itself, along with its
idandname.Returns Promise<void>
externalrecordExists
Tests whether a record with the given key exists in the key-value store without retrieving its value.
Parameters
externalkey: string
The queried record key.
Returns Promise<boolean>
trueif the record exists,falseif it does not.
externalsetValue
Saves or deletes a record in the key-value store. The function returns a promise that resolves once the record has been saved or deleted.
Example usage:
const store = await KeyValueStore.open();await store.setValue('OUTPUT', { foo: 'bar' });Beware that the key can be at most 256 characters long and only contain the following characters:
a-zA-Z0-9!-_.'()By default,
valueis converted to JSON and stored with theapplication/json; charset=utf-8MIME content type. To store the value with another content type, pass it in the options as follows:const store = await KeyValueStore.open('my-text-store');await store.setValue('RESULTS', 'my text data', { contentType: 'text/plain' });If you set custom content type,
valuemust be either a string orBuffer, otherwise an error will be thrown.If
valueisnull, the record is deleted instead. Note that thesetValue()function succeeds regardless whether the record existed or not.To retrieve a value from the key-value store, use the KeyValueStore.getValue function.
IMPORTANT: Always make sure to use the
awaitkeyword when callingsetValue(), otherwise the crawler process might finish before the value is stored!Parameters
externalkey: string
Unique key of the record. It can be at most 256 characters long and only consist of the following characters:
a-z,A-Z,0-9and!-_.'()externalvalue: null | T
Record data, which can be one of the following values:
- If
null, the record in the key-value store is deleted. - If no
options.contentTypeis specified,valuecan be any JavaScript object and it will be stringified to JSON. - If
options.contentTypeis set,valueis taken as is and it must be aStringorBuffer. For any other value an error will be thrown.
- If
externaloptionaloptions: RecordOptions
Record options.
Returns Promise<void>
externalvalues
Returns key-value store values.
When awaited (
await store.values()), returns all values as a flatT[]array. When used as an async iterable (for await...of), iterates over all values across pages without loading everything into memory at once.Example usage:
const keyValueStore = await KeyValueStore.open();// Iterate over all values (memory-efficient for large stores)for await (const value of keyValueStore.values()) {console.log(value);}// Or fetch all values at onceconst allValues = await keyValueStore.values();console.log(allValues);Parameters
externaloptionaloptions: KeyValueStoreIteratorOptions
Options for the iteration.
Returns AsyncIterable<T, any, any> & Promise<T[]>
staticexternalgetAutoSavedValue
Parameters
externalkey: string
externaloptionaldefaultValue: T
Returns Promise<T>
staticexternalopen
Opens a key-value store and returns a promise resolving to an instance of the KeyValueStore class.
Key-value stores are used to store records or files, along with their MIME content type. The records are stored and retrieved using a unique key. The actual data is stored either on a local filesystem or in the Apify cloud.
For more details and code examples, see the KeyValueStore class.
Parameters
externaloptionalidentifier: null | string | StorageIdentifier
ID or name of the key-value store to be opened. If a string is provided, it will first be looked up as an ID; if no such storage exists, it will be treated as a name. If
nullorundefined, the function returns the default key-value store associated with the crawler run.externaloptionaloptions: StorageOpenOptions
Storage manager options.
Returns Promise<KeyValueStore>
staticexternalrecordExists
Tests whether a record with the given key exists in the default KeyValueStore associated with the current crawler run.
Parameters
externalkey: string
The queried record key.
Returns Promise<boolean>
trueif the record exists,falseif it does not.
The
KeyValueStoreclass represents a key-value store, a simple data storage that is used for saving and reading data records or files. Each data record is represented by a unique key and associated with a MIME content type. Key-value stores are ideal for saving screenshots, crawler inputs and outputs, web pages, PDFs or to persist the state of crawlers.Do not instantiate this class directly, use the KeyValueStore.open function instead.
Each crawler run is associated with a default key-value store, which is created exclusively for the run. By convention, the crawler input and output are stored into the default key-value store under the
INPUTandOUTPUTkey, respectively. Typically, input and output are JSON files, although it can be any other format. To access the default key-value store directly, you can use the KeyValueStore.getValue and KeyValueStore.setValue convenience functions.KeyValueStorestores its data on a local disk.If the
CRAWLEE_STORAGE_DIRenvironment variable is set, the data is stored in the local directory in the following files:Note that
{STORE_ID}is the name or ID of the key-value store. The default key-value store has ID:default. The{KEY}is the key of the record and{EXT}corresponds to the MIME content type of the data value.Example usage: