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.

Docs/examples integration (#640)

Jan Bártad18c6fee3b8b
diff --git a/examples/basic_crawler.js b/examples/basic_crawler.js
deleted file mode 100644
index ec5f33dec..000000000
--- a/examples/basic_crawler.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * This is the most basic example of the Apify SDK, which demonstrates some of its
- * elementary tools, such as the
- * [`BasicCrawler`](/docs/api/basic-crawler)
- * and [`RequestList`](/docs/api/request-list) classes.
- * The script just downloads several web pages with plain HTTP requests using the
- * [`Apify.utils.requestAsBrowser()`](/docs/api/utils#requestasbrowser)
- * convenience function and stores their raw HTML and URL to the default dataset.
- * In local configuration, the data will be stored as JSON files in `./apify_storage/datasets/default`.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 on Alpine Linux (apify/actor-node-basic)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-// Apify.main() function wraps the crawler logic (it is optional).
-Apify.main(async () => {
- // Create and initialize an instance of the RequestList class that contains
- // a list of URLs to crawl. Here we use just a few hard-coded URLs.
- const requestList = new Apify.RequestList({
- sources: [
- { url: 'http://www.google.com/' },
- { url: 'http://www.example.com/' },
- { url: 'http://www.bing.com/' },
- { url: 'http://www.wikipedia.com/' },
- ],
- });
- await requestList.initialize();
-
- // Create a BasicCrawler - the simplest crawler that enables
- // users to implement the crawling logic themselves.
- const crawler = new Apify.BasicCrawler({
-
- // Let the crawler fetch URLs from our list.
- requestList,
-
- // This function will be called for each URL to crawl.
- // The 'request' option is an instance of the Request class, which contains
- // information such as URL and HTTP method, as supplied by the RequestList.
- handleRequestFunction: async ({ request }) => {
- console.log(`Processing ${request.url}...`);
-
- // Fetch the page HTML
- const { body } = await Apify.utils.requestAsBrowser(request);
-
- // Store the HTML and URL to the default dataset.
- await Apify.pushData({
- url: request.url,
- html: body,
- });
- },
- });
-
- // Run the crawler and wait for it to finish.
- await crawler.run();
-
- console.log('Crawler finished.');
-});
diff --git a/examples/call_actor.js b/examples/call_actor.js
deleted file mode 100644
index e638bfd52..000000000
--- a/examples/call_actor.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * This example demonstrates how to start an Apify actor using
- * [`Apify.call()`](/docs/api/apify#call) and how to call Apify API using
- * [`Apify.client`](/docs/api/apify#client).
- * The script extracts the current Bitcoin prices from [Kraken.com](https://www.kraken.com/)
- * and sends them to your email using the [`apify/send-mail`](https://apify.com/apify/send-mail) actor.
- *
- * To make the example work, you'll need an [Apify Account](https://my.apify.com/).
- * Go to [Account - Integrations](https://my.apify.com/account#/integrations) page to obtain your API token
- * and set it to the [`APIFY_TOKEN`](/docs/guides/environment-variables#apify_token) environment variable, or run the script using the CLI.
- * If you deploy this actor to the Apify Cloud then you can set up a scheduler for early
- * morning.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- // Launch the web browser.
- const browser = await Apify.launchPuppeteer();
-
- console.log('Obtaining email address...');
- const user = await Apify.client.users.getUser();
-
- // Load Kraken.com charts and get last traded price of BTC
- console.log('Extracting data from kraken.com...');
- const page = await browser.newPage();
- await page.goto('https://www.kraken.com/charts');
- const tradedPricesHtml = await page.$eval('#ticker-top ul', el => el.outerHTML);
-
- // Send prices to your email. For that, you can use an actor we already
- // have available on the platform under the name: apify/send-mail.
- // The second parameter to the Apify.call() invocation is the actor's
- // desired input. You can find the required input parameters by checking
- // the actor's documentation page: https://apify.com/apify/send-mail
- console.log(`Sending email to ${user.email}...`);
- await Apify.call('apify/send-mail', {
- to: user.email,
- subject: 'Kraken.com BTC',
- html: `<h1>Kraken.com BTC</h1>${tradedPricesHtml}`,
- });
-
- console.log('Email sent. Good luck!');
-});
diff --git a/examples/cheerio_crawler.js b/examples/cheerio_crawler.js
deleted file mode 100644
index b9d1eed63..000000000
--- a/examples/cheerio_crawler.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * This example demonstrates how to use [`CheerioCrawler`](/docs/api/cheerio-crawler)
- * to crawl a list of URLs from an external file,
- * load each URL using a plain HTTP request, parse the HTML using [cheerio](https://www.npmjs.com/package/cheerio)
- * and extract some data from it: the page title and all H1 tags.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 on Alpine Linux (apify/actor-node-basic)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-// Apify.utils contains various utilities, e.g. for logging.
-// Here we turn off the logging of unimportant messages.
-const { log } = Apify.utils;
-log.setLevel(log.LEVELS.WARNING);
-
-// A link to a list of Fortune 500 companies' websites available on GitHub.
-const CSV_LINK = 'https://gist.githubusercontent.com/hrbrmstr/ae574201af3de035c684/raw/f1000.csv';
-
-// Apify.main() function wraps the crawler logic (it is optional).
-Apify.main(async () => {
- // Create an instance of the RequestList class that contains a list of URLs to crawl.
- // Here we download and parse the list of URLs from an external file.
- const requestList = new Apify.RequestList({
- sources: [{ requestsFromUrl: CSV_LINK }],
- });
- await requestList.initialize();
-
- // Create an instance of the CheerioCrawler class - a crawler
- // that automatically loads the URLs and parses their HTML using the cheerio library.
- const crawler = new Apify.CheerioCrawler({
- // Let the crawler fetch URLs from our list.
- requestList,
-
- // The crawler downloads and processes the web pages in parallel, with a concurrency
- // automatically managed based on the available system memory and CPU (see AutoscaledPool class).
- // Here we define some hard limits for the concurrency.
- minConcurrency: 10,
- maxConcurrency: 50,
-
- // On error, retry each page at most once.
- maxRequestRetries: 1,
-
- // Increase the timeout for processing of each page.
- handlePageTimeoutSecs: 60,
-
- // This function will be called for each URL to crawl.
- // It accepts a single parameter, which is an object with the following fields:
- // - request: an instance of the Request class with information such as URL and HTTP method
- // - html: contains raw HTML of the page
- // - $: the cheerio object containing parsed HTML
- handlePageFunction: async ({ request, html, $ }) => {
- console.log(`Processing ${request.url}...`);
-
- // Extract data from the page using cheerio.
- const title = $('title').text();
- const h1texts = [];
- $('h1').each((index, el) => {
- h1texts.push({
- text: $(el).text(),
- });
- });
-
- // Store the results to the default dataset. In local configuration,
- // the data will be stored as JSON files in ./apify_storage/datasets/default
- await Apify.pushData({
- url: request.url,
- title,
- h1texts,
- html,
- });
- },
-
- // This function is called if the page processing failed more than maxRequestRetries+1 times.
- handleFailedRequestFunction: async ({ request }) => {
- console.log(`Request ${request.url} failed twice.`);
- },
- });
-
- // Run the crawler and wait for it to finish.
- await crawler.run();
-
- console.log('Crawler finished.');
-});
diff --git a/examples/forms.js b/examples/forms.js
deleted file mode 100644
index 3c0db4269..000000000
--- a/examples/forms.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * This example demonstrates how to use
- * [`PuppeteerCrawler`](/docs/api/puppeteer-crawler)
- * to automatically fill and submit a search form to look up repositories on
- * [GitHub](https://news.ycombinator.com)
- * using headless Chrome / Puppeteer.
- * The actor first fills in the search term, repository owner, start date and
- * language of the repository, then submits the form and prints out the results.
- * Finally, the results are saved either on the Apify platform to the default
- * [`Dataset`](/docs/api/dataset)
- * or on the local machine as JSON files in `./apify_storage/datasets/default`.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- // Launch the web browser.
- const browser = await Apify.launchPuppeteer();
-
- // Create and navigate new page
- console.log('Open target page');
- const page = await browser.newPage();
- await page.goto('https://github.com/search/advanced');
-
- // Fill form fields and select desired search options
- console.log('Fill in search form');
- await page.type('#adv_code_search input.js-advanced-search-input', 'apify-js');
- await page.type('#search_from', 'apifytech');
- await page.type('#search_date', '>2015');
- await page.select('select#search_language', 'JavaScript');
-
- // Submit the form and wait for full load of next page
- console.log('Submit search form');
- await Promise.all([
- page.waitForNavigation(),
- page.click('#adv_code_search button[type="submit"]')
- ]);
-
- // Obtain and print list of search results
- const results = await page.$$eval('div.codesearch-results ul.repo-list li h3 a', nodes => nodes.map(node => ({
- url: node.href,
- name: node.innerText
- })));
- console.log('Results:', results);
-
- // Store data in default dataset
- await Apify.pushData(results);
-});
diff --git a/examples/hello_world.js b/examples/hello_world.js
deleted file mode 100644
index f94254592..000000000
--- a/examples/hello_world.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Run the following example to perform a recursive crawl of a website using Puppeteer.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://www.iana.org/' });
- const pseudoUrls = [new Apify.PseudoUrl('https://www.iana.org/[.*]')];
-
- const crawler = new Apify.PuppeteerCrawler({
- requestQueue,
- handlePageFunction: async ({ request, page }) => {
- const title = await page.title();
- console.log(`Title of ${request.url}: ${title}`);
- await Apify.utils.enqueueLinks({ page, selector: 'a', pseudoUrls, requestQueue });
- },
- maxRequestsPerCrawl: 100,
- maxConcurrency: 10,
- });
-
- await crawler.run();
-});
diff --git a/examples/puppeteer_crawler.js b/examples/puppeteer_crawler.js
deleted file mode 100644
index f5bafde7e..000000000
--- a/examples/puppeteer_crawler.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * This example demonstrates how to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler)
- * in combination with [`RequestQueue`](/docs/api/request-queue) to recursively scrape the
- * [Hacker News website](https://news.ycombinator.com) using headless Chrome / Puppeteer.
- * The crawler starts with a single URL, finds links to next pages,
- * enqueues them and continues until no more desired links are available.
- * The results are stored to the default dataset. In local configuration, the results are stored as JSON files in `./apify_storage/datasets/default`
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- // Apify.openRequestQueue() is a factory to get a preconfigured RequestQueue instance.
- // We add our first request to it - the initial page the crawler will visit.
- const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://news.ycombinator.com/' });
-
- // Create an instance of the PuppeteerCrawler class - a crawler
- // that automatically loads the URLs in headless Chrome / Puppeteer.
- const crawler = new Apify.PuppeteerCrawler({
- requestQueue,
-
- // Here you can set options that are passed to the Apify.launchPuppeteer() function.
- launchPuppeteerOptions: {
- // For example, by adding "slowMo" you'll slow down Puppeteer operations to simplify debugging
- // slowMo: 500,
- },
-
- // Stop crawling after several pages
- maxRequestsPerCrawl: 10,
-
- // This function will be called for each URL to crawl.
- // Here you can write the Puppeteer scripts you are familiar with,
- // with the exception that browsers and pages are automatically managed by the Apify SDK.
- // The function accepts a single parameter, which is an object with the following fields:
- // - request: an instance of the Request class with information such as URL and HTTP method
- // - page: Puppeteer's Page object (see https://pptr.dev/#show=api-class-page)
- handlePageFunction: async ({ request, page }) => {
- console.log(`Processing ${request.url}...`);
-
- // A function to be evaluated by Puppeteer within the browser context.
- const pageFunction = ($posts) => {
- const data = [];
-
- // We're getting the title, rank and URL of each post on Hacker News.
- $posts.forEach(($post) => {
- data.push({
- title: $post.querySelector('.title a').innerText,
- rank: $post.querySelector('.rank').innerText,
- href: $post.querySelector('.title a').href,
- });
- });
-
- return data;
- };
- const data = await page.$$eval('.athing', pageFunction);
-
- // Store the results to the default dataset.
- await Apify.pushData(data);
-
- // Find a link to the next page and enqueue it if it exists.
- const infos = await Apify.utils.enqueueLinks({
- page,
- requestQueue,
- selector: '.morelink',
- });
-
- if (infos.length === 0) console.log(`${request.url} is the last page!`);
- },
-
- // This function is called if the page processing failed more than maxRequestRetries+1 times.
- handleFailedRequestFunction: async ({ request }) => {
- console.log(`Request ${request.url} failed too many times`);
- await Apify.pushData({
- '#debug': Apify.utils.createRequestDebugInfo(request),
- });
- },
- });
-
- // Run the crawler and wait for it to finish.
- await crawler.run();
-
- console.log('Crawler finished.');
-});
diff --git a/examples/puppeteer_sitemap.js b/examples/puppeteer_sitemap.js
deleted file mode 100644
index 0119e5bd8..000000000
--- a/examples/puppeteer_sitemap.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * This example demonstrates how to use [`PuppeteerCrawler`](/docs/api/puppeteer-crawler) to crawl a list of web pages
- * specified in a sitemap. The crawler extracts page title and URL from each page
- * and stores them as a record to the default dataset.
- * In local configuration, the results are stored as JSON files in `./apify_storage/datasets/default`
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- const requestList = new Apify.RequestList({
- sources: [{ requestsFromUrl: 'https://edition.cnn.com/sitemaps/cnn/news.xml' }],
- });
- await requestList.initialize();
-
- const crawler = new Apify.PuppeteerCrawler({
- requestList,
- handlePageFunction: async ({ page, request }) => {
- console.log(`Processing ${request.url}...`);
- await Apify.pushData({
- url: request.url,
- title: await page.title(),
- html: await page.content(),
- });
- },
- });
-
- await crawler.run();
- console.log('Done.');
-});
diff --git a/examples/puppeteer_with_proxy.js b/examples/puppeteer_with_proxy.js
deleted file mode 100644
index 8c0cf706f..000000000
--- a/examples/puppeteer_with_proxy.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * This example demonstrates how to load pages in headless Chrome / Puppeteer
- * over [Apify Proxy](https://docs.apify.com/proxy).
- * To make it work, you'll need an Apify Account that has access to the proxy.
- * The proxy password is available on the [Proxy](https://my.apify.com/proxy) page in the app.
- * Just set it to the [`APIFY_PROXY_PASSWORD`](../guides/environment-variables#apify_proxy_password)
- * environment variable or run the script using the CLI.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- // Apify.launchPuppeteer() is similar to Puppeteer's launch() function.
- // It accepts the same parameters and returns a preconfigured Puppeteer.Browser instance.
- // Moreover, it accepts several additional options, such as useApifyProxy.
- const options = {
- useApifyProxy: true,
- };
- const browser = await Apify.launchPuppeteer(options);
-
- console.log('Running Puppeteer script...');
-
- // Proceed with a plain Puppeteer script.
- const page = await browser.newPage();
- const url = 'https://en.wikipedia.org/wiki/Main_Page';
- await page.goto(url);
- const title = await page.title();
-
- console.log(`Page title: ${title}`);
-
- // Cleaning up after yourself is always good.
- await browser.close();
- console.log('Puppeteer closed.');
-});
diff --git a/examples/screenshots.js b/examples/screenshots.js
deleted file mode 100644
index d26234b3d..000000000
--- a/examples/screenshots.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * This example demonstrates how to read and write data to the default key-value store using
- * [`Apify.getValue()`](/docs/api/apify#getvalue) and [`Apify.setValue()`](/docs/api/apify#setvalue).
- *
- * The script crawls a list of URLs using Puppeteer,
- * captures a screenshot of each page and saves it to the store. The list of URLs is
- * provided as actor input that is also read from the store.
- *
- * In local configuration, the input is stored in the default key-value store's directory as a JSON file at
- * `./apify_storage/key_value_stores/default/INPUT.json`. You need to create the file and set it with the following content:
- *
- * ```json
- * { "sources": [{ "url": "https://www.google.com" }, { "url": "https://www.duckduckgo.com" }] }
- * ```
- *
- * On the Apify cloud, the input can be either set manually
- * in the UI app or passed as the POST payload to the
- * [Run actor API call](https://apify.com/docs/api/v2#/reference/actors/run-collection/run-actor).
- * For more details, see [Input and output](https://docs.apify.com/actor/run#input-and-output)
- * in the Apify Actor documentation.
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- // Read the actor input configuration containing the URLs for the screenshot.
- // By convention, the input is present in the actor's default key-value store under the "INPUT" key.
- const input = await Apify.getInput();
- if (!input) throw new Error('Have you passed the correct INPUT ?');
-
- const { sources } = input;
-
- const requestList = new Apify.RequestList({ sources });
- await requestList.initialize();
-
- const crawler = new Apify.PuppeteerCrawler({
- requestList,
- handlePageFunction: async ({ page, request }) => {
- console.log(`Processing ${request.url}...`);
-
- // This is a Puppeteer function that takes a screenshot of the page and returns its buffer.
- const screenshotBuffer = await page.screenshot();
-
- // The record key may only include the following characters: a-zA-Z0-9!-_.'()
- const key = request.url.replace(/[:/]/g, '_');
-
- // Save the screenshot. Choosing the right content type will automatically
- // assign the local file the right extension, in this case .png.
- // The screenshots will be stored in ./apify_storage/key_value_stores/default/
- await Apify.setValue(key, screenshotBuffer, { contentType: 'image/png' });
- console.log(`Screenshot of ${request.url} saved.`);
- },
- });
-
- // Run crawler.
- await crawler.run();
-
- console.log('Crawler finished.');
-});
diff --git a/examples/synchronous_run.js b/examples/synchronous_run.js
deleted file mode 100644
index 4a8838d79..000000000
--- a/examples/synchronous_run.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * This example shows a quick actor that has a run time of just a few seconds.
- * It opens a [web page](http://goldengatebridge75.org/news/webcam.html)
- * that contains a webcam stream from the Golden Gate Bridge, takes a screenshot of the page and saves it as output.
- *
- * This actor
- * can be invoked synchronously using a single HTTP request to directly obtain its output as a response, using the
- * [Run actor synchronously](https://apify.com/docs/api/v2#/reference/actors/run-actor-synchronously/without-input)
- * Apify API endpoint. The example is also shared as the
- * [`apify/example-golden-gate-webcam`](https://apify.com/apify/example-golden-gate-webcam)
- * actor in the Apify library, so you can test it directly there simply by sending a POST request to
- * ```http
- * https://api.apify.com/v2/acts/apify~example-golden-gate-webcam/run-sync?token=[YOUR_API_TOKEN]
- * ```
- *
- * To run this example on the Apify Platform, select the `Node.js 12 + Chrome on Debian (apify/actor-node-chrome)` base image
- * on the source tab of your actor configuration.
- */
-
-const Apify = require('apify');
-
-Apify.main(async () => {
- // Launch web browser.
- const browser = await Apify.launchPuppeteer({ headless: true });
-
- // Load http://goldengatebridge75.org/news/webcam.html and get an IFRAME with the webcam stream
- console.log('Opening web page...');
- const page = await browser.newPage();
- await page.goto('http://goldengatebridge75.org/news/webcam.html');
- const frames = await page.frames();
- const iframeWithVideo = frames[1];
-
- // Wait for the webcam to load.
- console.log('Waiting for the webcam image.');
- const imageElementHandle = await iframeWithVideo.waitForSelector('.VideoColm img[src^="blob:"]');
- // Wait a little more to give the browser a chance to display the image.
- await page.waitFor(1000);
-
- // Get a screenshot of that image.
- const imageBuffer = await imageElementHandle.screenshot();
- console.log('Screenshot captured.');
-
- // Save the screenshot as the actor's output. By convention, similarly to "INPUT",
- // the actor's output is stored in the default key-value store under the "OUTPUT" key.
- await Apify.setValue('OUTPUT', imageBuffer, { contentType: 'image/jpeg' });
- console.log('Actor finished.');
-});
diff --git a/src/constants.js b/src/constants.js
index 754750226..e6845ba1a 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -2,9 +2,9 @@ import { ACTOR_EVENT_NAMES } from 'apify-shared/consts';
/**
* The default user agent used by `Apify.launchPuppeteer`.
- * Last updated on 2018-12-30.
+ * Last updated on 2020-04-08.
*/
-export const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'; // eslint-disable-line max-len
+export const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36'; // eslint-disable-line max-len
/**
* Exit codes for the actor process.
diff --git a/website/package.json b/website/package.json
index 0395f2290..9b56fbb38 100644
--- a/website/package.json
+++ b/website/package.json
@@ -19,6 +19,7 @@
"fs-extra": "^8.1.0"
},
"dependencies": {
+ "@apify/http-request": "^1.1.5",
"remarkable-extlink": "^1.1.0"
}
}
diff --git a/website/siteConfig.js b/website/siteConfig.js
index 39f1708a0..6c2438edb 100644
--- a/website/siteConfig.js
+++ b/website/siteConfig.js
@@ -47,7 +47,7 @@ const siteConfig = {
headerLinks: [
{ search: true },
{ doc: 'guides/motivation', label: 'Guide' },
- { doc: 'examples/basic-crawler', label: 'Examples' },
+ { doc: 'examples/accept-user-input', label: 'Examples' },
{ doc: 'api/apify', label: 'API Reference' },
{ href: repoUrl, label: 'GitHub' },
// { page: 'help', label: 'Help' },
diff --git a/website/tools/build_docs.js b/website/tools/build_docs.js
index 38d8a648d..e182e57dc 100644
--- a/website/tools/build_docs.js
+++ b/website/tools/build_docs.js
@@ -3,12 +3,16 @@ const fs = require('fs-extra');
const jsdoc2md = require('jsdoc-to-markdown'); // eslint-disable-line
const path = require('path');
const prettier = require('prettier'); // eslint-disable-line
-const readline = require('readline');
+const httpRequest = require('@apify/http-request');
const prettierConfig = require('./prettier.config');
+const sidebars = require('../sidebars.json');
+const { readStreamToString } = require('apify-shared/streams_utilities'); // eslint-disable-line
const BASE_URL = '/docs';
+const DOCS_DIR = path.join(__dirname, '..', '..', 'docs');
+const EXAMPLES_DIR_NAME = path.join(DOCS_DIR, 'examples');
+const EXAMPLES_REPO = 'https://api.github.com/repos/apifytech/actor-templates/contents/dist/examples';
-/* eslint-disable no-shadow */
const classNames = [];
const namespaces = [];
@@ -45,23 +49,6 @@ const getRenderOptions = (template, data) => ({
],
});
-const readFileFromLine = async (path, lineNumber = 1) => {
- return new Promise((resolve, reject) => {
- const output = [];
- const rl = readline.createInterface({
- input: fs.createReadStream(path),
- crlfDelay: Infinity,
- });
- let lineCounter = 0;
- rl.on('line', (line) => {
- lineCounter++;
- if (lineCounter >= lineNumber) output.push(line);
- });
- rl.on('close', () => resolve(output.join('\n')));
- rl.on('error', err => reject(err));
- });
-};
-
const getLinkToEntity = (entityName, entityMap) => {
const entity = entityMap.get(entityName);
const folder = entity.kind === 'typedef' ? 'typedefs' : 'api';
@@ -132,32 +119,56 @@ const generateFinalMarkdown = (title, text, entityMap) => {
return prettier.format(header + text, prettierConfig);
};
+async function getExamplesFromRepo() {
+ await fs.emptyDir(EXAMPLES_DIR_NAME);
+ process.chdir(EXAMPLES_DIR_NAME);
+ const { body } = await httpRequest({
+ url: EXAMPLES_REPO,
+ json: true,
+ });
+ const builtExamples = await buildExamples(body);
+ await addExamplesToSidebars(builtExamples);
+}
+
+async function buildExamples(exampleLinks) {
+ const examples = [];
+ for (const example of exampleLinks) {
+ const responseStream = await httpRequest({
+ url: example.download_url,
+ stream: true,
+ });
+ try {
+ console.log(`Rendering example ${example.name}`);
+ const fileContent = await readStreamToString(responseStream);
+ const markdown = prettier.format(fileContent, prettierConfig);
+ fs.writeFileSync(example.name, markdown);
+ const exampleName = example.name.split('.')[0];
+ examples.push(`examples/${exampleName.replace(/_/g, '-')}`);
+ } catch (err) {
+ throw err;
+ }
+ }
+ return examples;
+}
+
+async function addExamplesToSidebars(examples) {
+ console.log('Saving examples to sidebars.json');
+ sidebars.examples = { Examples: examples };
+ fs.writeFileSync(path.join(__dirname, '..', 'sidebars.json'), JSON.stringify(sidebars, null, 4));
+}
+
+
const main = async () => {
/* input and output paths */
const sourceFiles = path.join(__dirname, '..', '..', 'src', '**', '*.js');
- const exampleFiles = path.join(__dirname, '..', '..', 'examples', '**', '*.js');
const sourceFilesOutputDir = path.join(__dirname, '..', '..', 'docs', 'api');
const typeFilesOutputDir = path.join(__dirname, '..', '..', 'docs', 'typedefs');
- const exampleFilesOutputDir = path.join(__dirname, '..', '..', 'docs', 'examples');
/* get template data */
const templateData = await jsdoc2md.getTemplateData({ files: sourceFiles });
- const exampleData = await jsdoc2md.getTemplateData({ files: exampleFiles });
// handle examples
- const examplePromises = exampleData.map(async (example) => {
- const { description, meta: { filename, path: filepath, lineno } } = example;
- const code = await readFileFromLine(path.join(filepath, filename), lineno);
- const sep = '```';
- const codeblock = `${sep}javascript\n${code}\n${sep}`;
-
- const title = filename.split('.')[0].split('_').map(word => `${word[0].toUpperCase()}${word.substr(1)}`).join(' ');
- const header = getHeader(title);
- const markdown = prettier.format(`${header}\n${description}\n${codeblock}`, prettierConfig);
- await fs.outputFile(path.join(exampleFilesOutputDir, `${title.replace(/\s/g, '')}.md`), markdown);
- });
-
- await Promise.all(examplePromises);
+ await getExamplesFromRepo();
/* reduce templateData to an array of class names */
templateData.forEach((identifier) => {