This topic provides examples on how to use official common layers.
Usage notes
To view the latest versions and the instructions for using official common layers, see awesome-layers.
Example 1: Sample program for capturing web page screenshots based on Node.js 16 and Puppeteer
Puppeteer is a Node.js library that provides a high-level API to control Chrome or Chromium over the DevTools protocol. Puppeteer is a headless Chrome browser that supports various automated processes, such as automatic webpage screenshot capturing, PDF generation, form submission, UI testing, and keyboard input simulation.
In this example, Puppeteer is used to implement a sample program to capture screenshots of web pages.
- Select Use Built-in Runtime to create a function. For more information, see Create a function. On the Create Function page, configure the following parameters and. Retain the default values of other parameters.
- Request Type: Select HTTP Requests.
- Runtime: Select Node.js 16 from the drop-down list.
- Memory Capacity: Select 1 GB.
- On the function details page, click the Code tab, edit the function code in the index.js file, and then click Deploy. Sample code:
const fs = require('fs'); const puppeteer = require('puppeteer'); function autoScroll(page) { return page.evaluate(() => { return new Promise((resolve, reject) => { var totalHeight = 0; var distance = 100; var timer = setInterval(() => { var scrollHeight = document.body.scrollHeight; window.scrollBy(0, distance); totalHeight += distance; if (totalHeight >= scrollHeight) { clearInterval(timer); resolve(); } }, 100); }) }); } module.exports.handler = function (request, response, context) { console.log('Node version is: ' + process.version); (async () => { const browser = await puppeteer.launch({ headless: true, args: [ '--disable-gpu', '--disable-dev-shm-usage', '--disable-setuid-sandbox', '--no-first-run', '--no-zygote', '--no-sandbox' ] }); let url = request.queries['url']; if (!url) { url = 'https://www.serverless-devs.com'; } if (!url.startsWith('https://') && !url.startsWith('http://')) { url = 'http://' + url; } const page = await browser.newPage(); await page.emulateTimezone('Asia/Shanghai'); await page.goto(url, { 'waitUntil': 'networkidle2' }); await page.setViewport({ width: 1200, height: 800 }); await autoScroll(page) let path = '/tmp/example'; let contentType = 'image/png'; await page.screenshot({ path: path, fullPage: true, type: 'png' }); await browser.close(); response.setStatusCode(200); response.setHeader('content-type', contentType); response.send(fs.readFileSync(path)) })().catch(err => { response.setStatusCode(500); response.setHeader('content-type', 'text/plain'); response.send(err.message); }); };
In the preceding sample code: First, the
query
parameter is parsed to obtain the URL of the web page whose screenshot you want to capture. If the parsing fails, the homepage of Serverless Devs is used. Then, Puppeteer is used to capture a screenshot of the web page and save the screenshot to the /tmp/example folder of the running instance. At last, the path is returned as the response body of the HTTP request. - Configure the Puppeteer common layer for the function. For more information, see Configure common layers by using the console. Use the official common layer Puppeteer17x.Important If your runtime environment is not Node.js 16, you must add environment variables. For more information, see Nodejs-Puppeteer17x README.
- On the function details page, click the Trigger Management (URL) tab. In the Configurations column of the trigger, click the test URL to download the configuration script. After the script is executed, you can use the test URL to perform the test in a browser. Important Before you use the test URL to perform a test, click the test URL. In the panel that appears, download and run the configuration script that is suitable for your operating system.
Example 2: Implementation of a .NET 6 custom runtime based on common layers
- Create a function by selecting Use Custom Runtime. For more information, see Create a function. On the Create Function page, configure the following parameters and retain the default values of other parameters.
- Request Type: Select HTTP Requests.
- Runtime: Select .NET 6.0.
After the function is created, you can view the Program.cs sample code on the web IDE.- ①: This sample program listens on port 9000 port of
0.0.0.0
. Services that are started in a custom runtime must listen on0.0.0.0:CAPort
or*:CAPort
and cannot listen on127.0.0.1
orlocalhost
. For more information, see Basic principles. - ②: Add the / route and return the
"Hello World!"
string. - ③: Add the /invoke route that uses the path of an event handler. For more information, see Event handlers
- ④: Add the /initialize route, which is the path that corresponds to the Initializer hook of the function. The Initializer hook is executed once during the initialization of the sample program. For more information, see Lifecycle hooks for function instances
- Test the function. Important Before you use the test URL to perform a test, click the test URL. In the panel that appears, download and run the configuration script that is suitable for your operating system.