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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
fix: update utils.purgeLocalStorage to mimic 'purge' param of 'apify run' (#1355)
Andrey Bykovb9b77ccf94aa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2fe87f7ee..dab11a693 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,3 +1,7 @@+2.3.3 / TBA+====================+- fix: update `purgeLocalStorage` utility method to mimic `purge` param of `apify run`+2.3.2 / 2022/05/05====================- fix: use default user agent for playwright with chrome instead of the default "headless UA"diff --git a/package.json b/package.jsonindex f9a926d52..7c0c17a99 100644--- a/package.json+++ b/package.json@@ -66,7 +66,6 @@"jquery": "^3.6.0","mime-types": "^2.1.35","ow": "^0.28.1",- "rimraf": "^3.0.2","semver": "^7.3.7","stream-json": "^1.7.4","tough-cookie": "^4.0.0",@@ -122,6 +121,7 @@"proxy": "^1.0.2","proxy-chain": "^2.0.1","puppeteer": "13.7.0",+ "rimraf": "^3.0.2","sinon": "^12.0.0","sinon-stub-promise": "^4.0.0","ts-jest": "^27.0.5",diff --git a/src/utils.js b/src/utils.jsindex 2e40eb622..936d023ea 100644--- a/src/utils.js+++ b/src/utils.js@@ -2,11 +2,11 @@ import psTree from '@apify/ps-tree';import { execSync } from 'child_process';import { ApifyClient } from 'apify-client';import { version as apifyClientVersion } from 'apify-client/package.json';-import { ACT_JOB_TERMINAL_STATUSES, ENV_VARS } from '@apify/consts';+import { ACT_JOB_TERMINAL_STATUSES, ENV_VARS, LOCAL_ENV_VARS, LOCAL_STORAGE_SUBDIRS, KEY_VALUE_STORE_KEYS } from '@apify/consts';// eslint-disable-next-line import/no-duplicatesimport cheerio from 'cheerio';import contentTypeParser from 'content-type';-import fs from 'fs';+import fs from 'fs-extra';import mime from 'mime-types';import os from 'os';import ow from 'ow';@@ -15,7 +15,6 @@ import semver from 'semver';import _ from 'underscore';import { URL } from 'url';import util from 'util';-import rimraf from 'rimraf';// TYPE IMPORTS/* eslint-disable no-unused-vars,import/named,import/no-duplicates,import/order */@@ -30,8 +29,6 @@ import { CheerioAPI } from 'cheerio';import { Configuration } from './configuration';/* eslint-enable no-unused-vars,import/named,import/no-duplicates,import/order */-const rimrafp = util.promisify(rimraf);-/*** Default regular expression to match URLs in a string that may be plain text, JSON, CSV or other. It supports common URL characters* and does not support URLs containing commas or spaces. The URLs also may contain Unicode letters (not symbols).@@ -748,10 +745,10 @@ export const waitForRunToFinish = async (options) => {};/**- * Cleans up the local storage folder created when testing locally.- * This is useful in the event you are debugging your code locally.- *- * Be careful as this will remove the folder you provide and everything in it!+ * Cleans up the default local storage directories before the run starts:+ * - local directory containing the default dataset;+ * - all records from the default key-value store in the local directory, except for the "INPUT" key;+ * - local directory containing the default request queue.** @param {string} [folder] The folder to clean up* @returns {Promise<void>}@@ -761,12 +758,37 @@ export const waitForRunToFinish = async (options) => {*/export const purgeLocalStorage = async (folder) => {// If the user did not provide a folder, try to get it from the env variables, or the default one- if (!folder) {- folder = process.env[ENV_VARS.LOCAL_STORAGE_DIR] || 'apify_storage';- }+ if (!folder) folder = process.env[ENV_VARS.LOCAL_STORAGE_DIR] || 'apify_storage';++ const defaultDatasetPath = path.resolve(folder, LOCAL_STORAGE_SUBDIRS.datasets, LOCAL_ENV_VARS[ENV_VARS.DEFAULT_DATASET_ID]);+ await removeFiles(defaultDatasetPath);++ const defaultKeyValueStorePath = path.resolve(folder, LOCAL_STORAGE_SUBDIRS.keyValueStores, LOCAL_ENV_VARS[ENV_VARS.DEFAULT_KEY_VALUE_STORE_ID]);+ await removeFiles(defaultKeyValueStorePath);++ const defaultRequestQueuePath = path.resolve(folder, LOCAL_STORAGE_SUBDIRS.requestQueues, LOCAL_ENV_VARS[ENV_VARS.DEFAULT_REQUEST_QUEUE_ID]);+ await removeFiles(defaultRequestQueuePath);+};++/**+ * @ignore+ */+const removeFiles = async (folder) => {+ const storagePathExists = await fs.pathExists(folder);++ if (storagePathExists) {+ const direntNames = await fs.readdir(folder);- // Clear the folder- await rimrafp(folder);+ const deletePromises = [];+ for (const direntName of direntNames) {+ const fileName = path.join(folder, direntName);+ if (!RegExp(KEY_VALUE_STORE_KEYS.INPUT).test(fileName)) {+ deletePromises.push(fs.rm(fileName, { recursive: true, force: true }));+ }+ }++ await Promise.all(deletePromises);+ }};/**diff --git a/test/utils.test.js b/test/utils.test.jsindex d7566b3d8..841fa37dc 100644--- a/test/utils.test.js+++ b/test/utils.test.js@@ -1,11 +1,11 @@import sinon from 'sinon';import _ from 'underscore';-import fs from 'fs';+import fs from 'fs-extra';import path from 'path';import os from 'os';import cheerio from 'cheerio';import semver from 'semver';-import { ENV_VARS } from '@apify/consts';+import { ENV_VARS, LOCAL_STORAGE_SUBDIRS } from '@apify/consts';import { addTimeoutToPromise } from '@apify/timeout';import { Log, LoggerText } from '@apify/log';import Apify from '../build/index';@@ -931,19 +931,64 @@ describe('utils.parseContentTypeFromResponse', () => {});describe('utils.purgeLocalStorage()', () => {- // Create test folder- const folder = Date.now().toString(16);- fs.mkdirSync(folder);+ const folders = [];+ let customFolder;++ beforeAll(async () => {+ process.env[ENV_VARS.LOCAL_STORAGE_DIR] = path.resolve('test/tmp', `./test_storage_${Date.now().toString(16)}`);+ folders.push(process.env[ENV_VARS.LOCAL_STORAGE_DIR]);++ customFolder = path.resolve('test/tmp', Date.now().toString(16));+ folders.push(customFolder);++ for (const folder of folders) {+ for (const storage in LOCAL_STORAGE_SUBDIRS) { // eslint-disable-line+ const subFolder = LOCAL_STORAGE_SUBDIRS[storage];++ for (const storageName of ['default', 'non-default']) {+ const storagePath = path.resolve(folder, subFolder, storageName);+ await fs.ensureDir(storagePath);++ const fileData = JSON.stringify({ foo: 'bar' });+ await fs.writeFile(path.join(storagePath, '000000001.json'), fileData);++ if (storage === 'keyValueStores') {+ await fs.writeFile(path.join(storagePath, 'INPUT.json'), fileData);+ }+ }+ }+ }+ });++ afterAll(async () => {+ await fs.rm('test/tmp', { recursive: true, force: true });+ });test('should purge local storage by default', async () => {await expect(utils.purgeLocalStorage()).resolves.toBeUndefined();-- expect(fs.existsSync('apify_storage')).toBe(false);+ const folder = process.env[ENV_VARS.LOCAL_STORAGE_DIR];+ // default storages should be empty, except INPUT.json file+ expect(fs.readdirSync(path.join(folder, 'datasets', 'default')).length).toBe(0);+ expect(fs.readdirSync(path.join(folder, 'key_value_stores', 'default')).length).toBe(1);+ expect(fs.readdirSync(path.join(folder, 'key_value_stores', 'default'))[0]).toBe('INPUT.json');+ expect(fs.readdirSync(path.join(folder, 'request_queues', 'default')).length).toBe(0);+ // non-default storages should keep their state and should not be cleared+ expect(fs.readdirSync(path.join(folder, 'datasets', 'non-default')).length).toBe(1);+ expect(fs.readdirSync(path.join(folder, 'key_value_stores', 'non-default')).length).toBe(2);+ expect(fs.readdirSync(path.join(folder, 'request_queues', 'non-default')).length).toBe(1);});test('should purge local storage when passing custom name', async () => {- await expect(utils.purgeLocalStorage(folder)).resolves.toBeUndefined();-- expect(fs.existsSync(folder)).toBe(false);+ await expect(utils.purgeLocalStorage(customFolder)).resolves.toBeUndefined();+ const folder = customFolder;+ // default storages should be empty, except INPUT.json file+ expect(fs.readdirSync(path.join(folder, 'datasets', 'default')).length).toBe(0);+ expect(fs.readdirSync(path.join(folder, 'key_value_stores', 'default')).length).toBe(1);+ expect(fs.readdirSync(path.join(folder, 'key_value_stores', 'default'))[0]).toBe('INPUT.json');+ expect(fs.readdirSync(path.join(folder, 'request_queues', 'default')).length).toBe(0);+ // non-default storages should keep their state and should not be cleared+ expect(fs.readdirSync(path.join(folder, 'datasets', 'non-default')).length).toBe(1);+ expect(fs.readdirSync(path.join(folder, 'key_value_stores', 'non-default')).length).toBe(2);+ expect(fs.readdirSync(path.join(folder, 'request_queues', 'non-default')).length).toBe(1);});});