Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

add getPublicUrl function to key-value-store

aarontjdevd15303672d96
diff --cc CHANGELOG.md
index 0cc1c57d4,519a91849..1909c8a3a
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -1,6 -1,73 +1,79 @@@
++<<<<<<< HEAD
+xxx
+===================
+- Added `getPublicUrl` function to `KeyValueStoreLocal`
++=======
+ 0.11.5 / 2018-01-18
+ ===================
+ - Disabled the `PuppeteerPool` `reusePages` option for now, due to a memory leak.
+ - Added a `keyValueStore.forEachKey()` method to iterate all keys in the store.
+
+ 0.11.4 / 2018-01-15
+ ===================
+ - Improvements in `Apify.utils.social.parseHandlesFromHtml` and `Apify.utils.htmlToText`
+ - Updated docs
+
+ 0.11.3 / 2018-01-10
+ ===================
+ - Fix `reusePages` causing Puppeteer to fail when used together with request interception.
+
+ 0.11.2 / 2018-01-10
+ ===================
+ - Fix missing `reusePages` configuration parameter in `PuppeteerCrawler`.
+ - Fix a memory leak where `reusePages` would prevent browsers from closing.
+
+ 0.11.1 / 2018-01-07
+ ===================
+ - Fix missing `autoscaledPool` parameter in `handlePageFunction` of `PuppeteerCrawler`.
+
+ 0.11.0 / 2018-01-07
+ ===================
+ - **BREAKING CHANGE:** `basicCrawler.abort()`, `cheerioCrawler.abort()` and `puppeteerCrawler.abort()` functions
+ were removed in favor of a single `autoscaledPool.abort()` function.
+
+ - Added a reference to the running `AutoscaledPool` instance to the options object of `BasicCrawler`'s
+ `handleRequestFunction` and to the `handlePageFunction` of `CheerioCrawler` and `PuppeteerCrawler`.
+ - Added sources persistence option to `RequestList` that works best in conjunction with the state persistence,
+ but can be toggled separately too.
+ - Added `Apify.openRequestList()` function to place it in line with `RequestQueue`, `KeyValueStore` and `Dataset`.
+ `RequestList` created using this function will automatically persist state and sources.
+ - Added `pool.pause()` and `pool.resume()` functions to `AutoscaledPool`. You can now pause the pool,
+ which will prevent additional tasks from being run and wait for the running ones to finish.
+ - Fixed a memory leak in `CheerioCrawler` and potentially other crawlers.
+
+ 0.10.2 / 2018-12-30
+ ===================
+ - Added `Apify.utils.htmlToText()` function to convert HTML to text and removed unncessary `html-to-text` dependency.
+ The new function is now used in `Apify.utils.social.parseHandlesFromHtml()`.
+ - Updated `DEFAULT_USER_AGENT`
+
+ 0.10.0 / 2018-12-19
+ ===================
+ - `autoscaledPool.isFinishedFunction()` and `autoscaledPool.isTaskReadyFunction()` exceptions
+ will now cause the `Promise` returned by `autoscaledPool.run()` to reject instead of just
+ logging a message. This is in line with the `autoscaledPool.runTaskFunction()` behavior.
+ - Bugfix: PuppeteerPool was incorrectly overriding `proxyUrls` even if they were not defined.
+ - Fixed an issue where an error would be thrown when `datasetLocal.getData()` was invoked
+ with an overflowing offset. It now correctly returns an empty `Array`.
+ - Added the `reusePages` option to `PuppeteerPool`. It will now reuse existing tabs
+ instead of opening new ones for each page when enabled.
+ - `BasicCrawler` (and therefore all Crawlers) now logs a message explaining why it finished.
+ - Fixed an issue where `maxRequestsPerCrawl` option would not be honored after restart or migration.
+ - Fixed an issue with timeout promises that would sometimes keep the process hanging.
+ - `CheerioCrawler` now accepts `gzip` and `deflate` compressed responses.
+
+ 0.9.15 / 2018-11-30
+ ===================
+ - Upgraded Puppeteer to 1.11.0
+ - **DEPRECATION WARNING:** `Apify.utils.puppeteer.enqueueLinks()` now uses an options object instead of individual parameters
+ and supports passing of `userData` to the enqueued `request`. Previously: `enqueueLinks(page, selector, requestQueue, pseudoUrls)`
+ Now: `enqueueLinks({ page, selector, requestQueue, pseudoUrls, userData })`. Using individual parameters is **DEPRECATED**.
+
+ 0.9.14 / 2018-11-27
+ ===================
+ - Added API response tracking to AutoscaledPool, leveraging `Apify.client.stats` object. It now overloads the system
+ when a large amount of 429 - Too Many Requests is received.
++>>>>>>> upstream/master
0.9.13 / 2018-11-26
===================
diff --cc src/key_value_store.js
index 051e63337,36f8fda5f..a34d9c198
--- a/src/key_value_store.js
+++ b/src/key_value_store.js
@@@ -291,10 -291,42 +292,48 @@@ export class KeyValueStore
});
}
++
+ getPublicUrl(fileName) {
+ ensureTokenOrLocalStorageEnvExists('key value store');
+ return `${publicUrl}/${this.storeId}/records/${fileName}`;
+ }
++
+ /**
+ * Iterates over key value store keys, yielding each in turn to an `iteratee` function.
+ * Each invocation of `iteratee` is called with two arguments: `(item, index)`.
+ *
+ * If the `iteratee` function returns a Promise then it is awaited before the next call.
+ * If it throws an error, the iteration is aborted and the `forEachKey` function throws the error.
+ *
+ * **Example usage**
+ * ```javascript
+ * const keyValueStore = await Apify.openKeyValueStore();
+ * keyValueStore.forEachKey(async (key, index) => {
+ * console.log(`Key at ${index}: ${key}`);
+ * });
+ * ```
+ *
+ * @param {Function} iteratee A function that is called for every key in the key value store.
+ * @param {Object} [options] All `forEachKey()` parameters are passed
+ * via an options object with the following keys:
+ * @param {string} [options.exclusiveStartKey] All keys up to this one (including) are skipped from the result.
+ * @return {Promise}
+ */
+ async forEachKey(iteratee, options = {}, index = 0) {
+ const { exclusiveStartKey } = options;
+ checkParamOrThrow(iteratee, 'iteratee', 'Function');
+ checkParamOrThrow(exclusiveStartKey, 'options.exclusiveStartKey', 'Maybe String');
+ checkParamOrThrow(index, 'index', 'Number');
+
+ const response = await keyValueStores.listKeys({ storeId: this.storeId, exclusiveStartKey });
+ const { nextExclusiveStartKey, isTruncated, items } = response.data;
+ for (const key of items) {
+ await iteratee(key, index++);
+ }
+ return isTruncated
+ ? this.forEachKey(iteratee, { exclusiveStartKey: nextExclusiveStartKey }, index)
+ : undefined; // [].forEach() returns undefined.
+ }
}
/**
diff --cc test/key_value_store.js
index 6551ffee3,2d791b95d..e60e361f3
--- a/test/key_value_store.js
+++ b/test/key_value_store.js
@@@ -367,22 -367,88 +368,109 @@@ describe('KeyValueStore', () =>
});
});
++
+ describe('getPublicUrl', () => {
+ it('should return the local url of a file', () => {
+ process.env[ENV_VARS.LOCAL_STORAGE_DIR] = LOCAL_STORAGE_DIR;
+ const store = new KeyValueStoreLocal('my-store-id', LOCAL_STORAGE_DIR);
+
+ expect(store.getPublicUrl('file','my-store-id')).to.equal(`file:/${store.localStoragePath}/my-store-id/file`);
+ delete process.env[ENV_VARS.LOCAL_STORAGE_DIR];
+ });
+
+ it('should return the url of a file in apify cloud', async () => {
+ process.env[ENV_VARS.TOKEN] = 'xxx';
+ const publicUrl = 'https://api.apify.com/v2/key-value-stores';
+ const store = new KeyValueStore('my-store-id');
+
+ expect(store.getPublicUrl('file')).to.equal(`${publicUrl}/my-store-id/records/file`);
+ delete process.env[ENV_VARS.TOKEN];
- })
++
++ });
++ });
++
+ describe('forEachKey', () => {
+ it('should work remotely', async () => {
+ const storeId = 'some-id-1';
+ const store = new KeyValueStore(storeId, 'some-name-1');
+ const mock = sinon.mock(apifyClient.keyValueStores);
+
+ mock.expects('listKeys')
+ .once()
+ .withArgs({
+ storeId,
+ exclusiveStartKey: 'key0',
+ })
+ .resolves({
+ data: {
+ isTruncated: true,
+ nextExclusiveStartKey: 'key2',
+ items: ['key1', 'key2'],
+ },
+ });
+ mock.expects('listKeys')
+ .once()
+ .withArgs({
+ storeId,
+ exclusiveStartKey: 'key2',
+ })
+ .resolves({
+ data: {
+ isTruncated: true,
+ nextExclusiveStartKey: 'key4',
+ items: ['key3', 'key4'],
+ } });
+ mock.expects('listKeys')
+ .once()
+ .withArgs({
+ storeId,
+ exclusiveStartKey: 'key4',
+ })
+ .resolves({
+ data: {
+ isTruncated: false,
+ nextExclusiveStartKey: null,
+ items: ['key5'],
+ } });
+
+ const results = [];
+ await store.forEachKey(async (key, index) => {
+ results.push([key, index]);
+ }, { exclusiveStartKey: 'key0' });
+
+ expect(results).to.have.lengthOf(5);
+ results.forEach((r, i) => {
+ expect(r[1]).to.be.eql(i);
+ expect(r[0]).to.be.eql(`key${i + 1}`);
+ });
+
+ mock.verify();
+ });
+
+ it('should work locally', async () => {
+ const storeId = 'some-id-1';
+ const store = new KeyValueStoreLocal(storeId, LOCAL_STORAGE_DIR);
+
+ for (let i = 0; i < 10; i++) {
+ await store.setValue(`key${i}`, {});
+ }
+
+ const results = [];
+ await store.forEachKey((key, index) => {
+ results.push([key, index]);
+ }, { exclusiveStartKey: 'key3' });
+
+ expect(results).to.have.lengthOf(6);
+ results.forEach((r, i) => {
+ expect(r[1]).to.be.eql(i);
+ expect(r[0]).to.be.eql(`key${i + 4}`);
+ });
+
+ // Delete works.
+ const storeDir = path.join(LOCAL_STORAGE_DIR, LOCAL_STORAGE_SUBDIR, storeId);
+ expectDirNonEmpty(storeDir);
+ await store.delete();
+ expectDirEmpty(storeDir);
+ });
});
--});
++});