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
Fixed input/output keys, updated README.md, new unit tests
Jan Curn0f20ea339af9
diff --git a/README.md b/README.mdindex 5fea6694b..700a25a3f 100644--- a/README.md+++ b/README.md@@ -30,7 +30,7 @@ To simplify development of acts, the Actor runtime provides the `Apifier.main()`3) Waits for the user function to finish-4) Stores the output of the user function by calling `Apifier.setOutput()`+4) Stores the return value of the user function as act output by calling `Apifier.setOutput()`5) Exits the process@@ -38,43 +38,50 @@ If the user function throws an exception or some other error is encountered,then `Apifier.main()` prints the details to console so that it's saved into log file.`Apifier.main()` accepts a single argument - a user function that performs the act.-The simples use case is a syncronous user function.+The simples use case is a synchronous user function.```javascript-Apifier.main( (context) => {+Apifier.main((context) => {// my synchronous function that returns immediately- console.dir(context);- return 'Hello world from actor!';+ console.dir(context.input);+ return 'Output from my act!';});```-If the user function returns a promise, it is considered as asynchronous.+The user function accepts a single argument called `context`, which is described in the next section.++The return value from the user function is stored as output of the act.+It must be an object that can be stringified to JSON, otherwise the act will fail.+The output record will have the MIME content type set to `application/json; charset=utf-8`.++If the user function returns a promise, it is considered as asynchronous:```javascript-Apifier.main( (context) => {+Apifier.main((context) => {// my asynchronous function that returns a promise- console.dir(context);return Promise.resolve().then(() => {- return 'Hello world from asynchronous actor!';+ return 'Output from my act!';});});```-You can also take advantage of the async/await keywords:+In such case, the return value of the last function in the promise chain is considered as the act output.++To simplify your code, you can also take advantage of the async/await keywords:```javascriptconst request = require('request-promise');-Apifier.main( async (context) => {+Apifier.main(async (context) => {const result = await request('http://www.example.com');return result;});```-Note that you don't need to use `Apifier.main()` function at all,+Note that the `Apifier.main()` function does not need to be used at all,it is provided merely for user convenience. The same activity-can be performed using the lower-level functions described in the following text.+can be performed using the lower-level functions described in the following paragraphs.### Context@@ -117,20 +124,24 @@ such as `APIFY_INTERNAL_PORT` or `APIFY_STARTED_AT`, and the input is obtained bThe `context` object can be directly obtained as follows:```javascript-Apifier.getContext().then( (context) => {+Apifier.getContext().then((context) => {console.dir(context);});```### Input and output-Each act can have input and output data, which can be a string or binary data associated-with a MIME content type.+Each act can have an input and output data record, which is a string or binary buffer+with a specific MIME content type.+Both input and output is stored in the Apifier key-value store created specifically for the act run,+under keys `INPUT` and `OUTPUT`, respectively.+The ID of the key-value store is provided by the Actor runtime under `APIFY_DEFAULT_KEY_VALUE_STORE_ID`+environment variable.-To only obtain the input of the act, use the following code:+To obtain the input of the act, use the following code:```javascript-Apifier.getInput().then( (input) => {+Apifier.getInput().then((input) => {console.log(`Input in ${input.contentType}:`);console.dir(input.body);});@@ -143,15 +154,22 @@ const output = {body: 'test output from act',contentType: 'application/text'};-Apifier.setOutput(output).then( () => {+Apifier.setOutput(output).then(() => {console.log('Output saved!');});```+Note that this is especially useful if output of your act should not be a JSON,+because return value from `Apifier.main()` is always converted to JSON.++### Promises-Note that the `getContext`, `getInput` and `setOutput` also accept a Node.js-style callback parameter.-If the callback is not provided, they return a promise.+By default, the `getContext`, `getInput` and `setOutput` functions returns a promise.+However, they also accept a Node.js-style callback parameter;+if it is provided, the return value of the functions is not defined+and the functions only invoke the callback upon completion or error.+To set a promise dependency from an external library, use the following code:```javascriptdiff --git a/src/actor.js b/src/actor.jsindex 94c4dd2ab..4d763f1d1 100644--- a/src/actor.js+++ b/src/actor.js@@ -1,6 +1,6 @@import fs from 'fs';import ApifyClient from 'apify-client';-import { APIFY_ENV_VARS, EXIT_CODES } from './constants';+import { APIFY_ENV_VARS, EXIT_CODES, KV_STORE_KEYS } from './constants';import { getPromisesDependency, newPromise, nodeifyPromise } from './utils';/* global process */@@ -42,6 +42,7 @@ export const getInput = (callback = null) => {return apifyClient.keyValueStores.getRecord({storeId: getDefaultStoreIdOrThrow(),promise: getPromisesDependency(),+ key: KV_STORE_KEYS.INPUT,}, callback);};@@ -61,6 +62,7 @@ export const setOutput = (output, callback = null) => {return apifyClient.keyValueStores.putRecord({storeId: getDefaultStoreIdOrThrow(),promise: getPromisesDependency(),+ key: KV_STORE_KEYS.OUTPUT,body: output.body,contentType: output.contentType,}, callback);diff --git a/src/constants.js b/src/constants.jsindex 7b2178a13..4326f71d3 100644--- a/src/constants.js+++ b/src/constants.js@@ -22,3 +22,9 @@ export const APIFY_ENV_VARS = {DEFAULT_KEY_VALUE_STORE_ID: 'APIFY_DEFAULT_KEY_VALUE_STORE_ID',WATCH_FILE: 'APIFY_WATCH_FILE',};+++export const KV_STORE_KEYS = {+ INPUT: 'INPUT',+ OUTPUT: 'OUTPUT',+};diff --git a/test/actor.js b/test/actor.jsindex 16e820c2b..997f93a9e 100644--- a/test/actor.js+++ b/test/actor.js@@ -158,6 +158,7 @@ const testMain = ({ userFunc, context, exitCode, mockInputException, mockOutputE.withExactArgs({storeId: context.defaultKeyValueStoreId,promise: Apifier.getPromisesDependency(),+ key: 'INPUT',}, null).returns(Promise.resolve(context.input)).once();@@ -178,6 +179,7 @@ const testMain = ({ userFunc, context, exitCode, mockInputException, mockOutputE.withExactArgs({storeId: context.defaultKeyValueStoreId,promise: Apifier.getPromisesDependency(),+ key: 'OUTPUT',contentType: expectedOutput.contentType,body: expectedOutput.body,}, null)@@ -325,6 +327,7 @@ describe('Apifier.getContext()', () => {.withExactArgs({storeId: expectedContext.defaultKeyValueStoreId,promise: Apifier.getPromisesDependency(),+ key: 'INPUT',}, null).once().returns(Promise.resolve(expectedContext.input));@@ -467,7 +470,7 @@ describe('Apifier.main()', () => {});});- it('on exception in setInput the process exits with code 1003', () => {+ it('on exception in setOutput the process exits with code 1003', () => {return testMain({userFunc: () => {return 'anything';@@ -479,6 +482,21 @@ describe('Apifier.main()', () => {mockOutputException: new Error('Text exception IV'),});});++ it('on non-JSON-stringifyable return value the process exits with code 1003', () => {+ const circularObj = {};+ circularObj.aaa = circularObj;++ return testMain({+ userFunc: () => {+ return circularObj;+ },+ context: {+ defaultKeyValueStoreId: 'test storeId',+ },+ exitCode: 1003,+ });+ });});