This document describes how to use a layer in the Serverless console.
Files in the layer are all under the /opt/
directory, which can be accessed through their absolute paths in the function code. In addition, the built-in environment variables of each runtime also include layer paths, so files can be uploaded according to such paths, and then they can be imported through their relative paths in the code.
For the environment variables in Python, Java, and Node.js, see the table below:
Environment Variable | Path |
---|---|
PYTHONPATH | /var/user:/opt |
CLASSPATH | /var/runtime/java8:/var/runtime/java8/lib/*:/opt |
NODE_PATH | /var/user:/var/user/node_modules:/var/lang/node6/lib/node_modules:/opt:/opt/node_modules |
The following takes importing the cos-nodejs-sdk-v5
dependency from node_modules
in a layer in the code in the Node.js runtime environment as an example:
Upload node_modules
to generate a layer as instructed in Creating layer. The local function directory structure is as shown below:
Package and upload the local function code as instructed in Deploying Function. During the packaging, run the following command to exclude the node_modules
folder:
zip -r package name.zip . -x "node_modules/*"
See the figure below:
Bind the created layer to the deployed function as instructed in Binding function to layer.
You can import files at the layer in the function after completing the steps above.
'use strict'
var COS = require('cos-nodejs-sdk-v5')
Note:
- As the
NODE_PATH
environment variable already includes the/opt/node_modules
path, there is no need to specify the absolute path of the dependency. SCF will load the file according to the path specified in the environment variable during execution.- If the file path in the layer and the path included in the environment variable are different, you need to use the absolute path when importing the file.
The following takes importing the cos-python-sdk-v5
dependency from a layer in the code in the Python runtime environment as an example:
cos-python-sdk-v5
to generate a layer as instructed in Creating layer.# -*- coding: utf8 -*-
import cos-python-sdk-v5
Note:
- As the
PYTHONPATH
environment variable already includes the/opt
path, there is no need to specify the absolute path of the dependency. SCF will load the file according to the path specified in the environment variable during execution.- If the file path in the layer and the path included in the environment variable are different, you need to use the absolute path when importing the file.
demo
as an example.layer
folder in the folder obtained in step 1.layerDemo
as an example.function
folder in the folder obtained in step 1.demo
created in step 2.
Was this page helpful?