Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to practice SCF Node.js Runtime of Cloud function

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

Many novices are not very clear about how to practice cloud function SCF Node.js Runtime. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can gain something.

Tencent Cloud function SCF recently released runtime for Node.js 12.16, which is also the first mainstream cloud service provider in China to support Node.js 12.x.

The upgrade of the Node.js version has brought new features and performance improvements. Interested students can refer to the article "Node.js 12: The future of server-side JavaScript" summarized by a foreign blogger for details.

One of the more important points is to improve the startup speed. With the support of v8 code cache, the code cache is generated for the built-in library ahead of time, and the startup time is increased by 30%.

Tencent Cloud function SCF is optimized for Node.js runtime in order to make Serverless more in line with the native experience of Node.js. I would like to take this opportunity to share with you how to use Tencent Cloud functions to develop Node.js applications and the principle of scf's Node.js runtime implementation.

Parameters of the entry function

First, let's look at the most basic Node.js entry function:

Exports.main_handler = (event, context, callback) = > {console.log ("Hello World"); console.log (event); console.log (context); callback (null, event);}

Runtime passes three parameters to the handler method.

The first parameter is event, which is used to pass trigger event data

Contains information from the caller. The caller passes this information as an JSON format string when it invokes, and the event structure varies from service to service.

The event object of the timing trigger includes the trigger time. The name of the trigger {Message: "", Time: "2020-05-08T14:30:00Z", TriggerName: "time_5", Type: "Timer"}

The event object of the apigateway trigger transmits the full content of the http request and the apigateway customized http request header information.

{"headerParameters": {}, "headers": {...}, "httpMethod": "GET", "path": "/ params_log", "pathParameters": {}, "queryString": {}, "queryStringParameters": {}, "requestContext": {"httpMethod": "ANY", "identity": {}, "path": "/ params_log", "serviceId": "service-9khp96qy", "sourceIp": "120.229.165", "stage": "release"}}

The event object of the cos trigger includes the specific cos operation that triggers the execution and the cos object.

{"Records": [{"cos": {"cosBucket": {"appid": "1251133793", "name": "test", "region": "gz"}, "cosNotificationId": "unkown", "cosObject": {"key": "/ 1251133793/test/xxx.png", "meta": {"Content-Type": "image/png", "x-cos-request-id": "NWViNTZmMmFfOTJhODQwYV80MGZmXzI0Y2ZkYmM="}, "size": 6545739, "url": "...", "vid": ""} "cosSchemaVersion": "eventQueue": "qcs:0:scf:ap-guangzhou:appid/1251133793:default.params_log.$DEFAULT", "eventSource": "qcs::cos", "eventTime": 1588948779, "eventVersion": "cosSchemaVersion", "reqid": 1038862404, "requestParameters": {"requestHeaders": {"Authorization": "..."}, "requestSourceIP": "120.229.9.165"} "reservedInfo": ""}}]}

The second parameter, context, is the function runtime information

Let's take a look at what a complete context contains:

CallbackWaitsForEmptyEventLoop: true,getRemainingTimeInMillis: 2008grammb: 128jndlmb: 3000environment: "{" SCF_NAMESPACE ":" demo "," TENCENTCLOUD_SECRETID ":"... "," TENCENTCLOUD_SECRETKEY ":"... "," TENCENTCLOUD_SESSIONTOKEN ":".} "function_name:" params ", function_version:" $LATEST ", namespace:" demo ", request_id:" ab42b693-8bfd-4dc1-b228-60360a63e06c " Tencentcloud_appid: "...", tencentcloud_region: "ap-chengdu", tencentcloud_uin: "..."

As you can see from the above, the object contains:

Function configuration information, such as set content size, timeout, etc.

Perform authentication information. If the running role of the function is set (the role must include the authorization policy for the corresponding operation), secretId,secretKey,sessionToken will be injected into the environment variable. When accessing third-party cloud services, such as cos and custom monitoring data reporting, you can use these values to directly call cloud api without having to hard code various key information in the code.

Environment variables: including user-defined environment variables and some system environment variables

Basic information of the execution environment: including the region of the current function call and the user's appId,uin

The third parameter, callback, is an optional parameter that returns the execution result in a non-asynchronous function.

The callback function takes two parameters: an Error and a return. The returned object must be compatible with JSON.stringify. Asynchronous functions ignore the return of callback and must handle the return or error through return, throw exception, or promise

Const https = require ('https') let url = "https://cloud.tencent.com/"exports.main_handler = function (event, context, callback) {https.get (url, (res) = > {callback (null, res.statusCode)}) .on (' error', (e) = > {callback (Error (e))})} function returns

Let's take a look at how the cloud function passes the return value for both asynchronous and non-asynchronous scenarios (async function)

Asynchronous function

For asynchronous functions, you can use return and throw to send returns or errors. The function must use the async keyword. In the asynchronous function, the third parameter, callback, is not defined

Example: asynchronous function

Const https = require ('https') let url = "https://cloud.tencent.com/"const httpRequest = url = > {const promise = new Promise (function (resolve, reject) {https .get (url, res = > {resolve (res.statusCode)}) .on (' error', e = > {reject (Error (e)})}) return promise} exports.handler = async function (event) Context) {try {const result = await httpRequest (url) / / callback is not defined in the async function / / callback (null, result) return result} catch (e) {throw e} synchronization function

Again, in the above example, initiate a http request. If you implement it with a synchronization function, refer to the following example

Example: synchronization function, returned by callback

Const https = require ('https') let url = "https://cloud.tencent.com/"exports.handler = function (event, context, callback) {https.get (url, (res) = > {/ / can only be returned through callback, return will be ignored callback (null, res.statusCode)}). On (' error', (e) = > {callback (Error (e)})} return time

After the normal Node.js web framework returns from the response, the asynchronous logic continues to execute. In the Serverless scenario, due to the difference between the mechanism and framework, for cases where responese has been returned, one is to wait for the asynchrony to be processed before returning, which ensures the integrity of a call. The other is to end the call directly after return and suspend asynchronous processing directly.

Tencent Cloud function implements a special mechanism for separating return and termination for the asynchronous scenario of Node.js.

After the synchronous execution of the entry function is completed and returned, the call to the cloud function returns immediately, and the return information of the code is returned to the function caller.

After the synchronous process is processed and returned, the asynchronous logic in the code can continue to be executed and processed, and the actual execution of the cloud function is not completed and exited until the asynchronous event execution is completed.

By default, function execution waits for all asynchronous execution to finish before a call ends, but it also gives the user the option to close the event loop wait, and the user can close the event loop to wait for the return time from the row control function. By setting context.callbackWaitsForEmptyEventLoop = false before the callback callback is executed, the cloud function can freeze the process immediately after the execution returns, instead of waiting for events in the asynchronous loop.

For example, in the sample code, an asynchronous http request is initiated and a setTimeout executed after 2s

Const https = require ('https') let url = "https://cloud.tencent.com/"const httpRequest = url = > {const promise = new Promise (function (resolve, reject) {https .get (url, res = > {resolve (res.statusCode)}) .on (' error', e = > {reject (Error (e)})}) return promise} exports.main_handler = async function (event) Context) {/ / set this option to false will not wait for the asynchronous queue to finish execution Instead, directly freeze process / / context.callbackWaitsForEmptyEventLoop = false try {const result = await httpRequest (url) setTimeout (() = > {console.log ('timeout log')}, 2000) return result} catch (e) {throw e}} after return

Immediately after the http request is completed, it is returned to the caller and does not wait for setTimeout's asynchronous practice to finish. After the return, the program will continue to execute until the event execution of the setTimeout is completed.

When context.callbackWaitsForEmptyEventLoop = false is set, the process will be frozen after return, and the execution logic in setTimeout will be suspended

Complete flow chart

The following is the complete flow chart of runtime running in a single instance

For Node.js applications, there are the following practical suggestions:

Log: runtime overrides several main methods of console, and it is after the require user file, so the user-defined log option will not be valid.

Cache reuse: variables can be defined outside the entry function to store reusable cache objects, such as database connections and other Node.js module implementation logic, if a module is require, the module will be cache to memory, and will not be reinitialized when it is require again. In view of this feature, if the instance is reused all the time, the variables defined outside the entry function will not be destroyed in the entry file, which can achieve the effect of reuse.

Built-in part of the npm package, you can use it directly, refer to the documentation. Npm install-production is recommended when deploying cloud function codes to reduce the size of the code package and increase the upload speed and execution speed.

Executive role: configure the executive role to obtain temporary key information from context, and access third-party services with appropriate permissions without having to write dead key information in the code.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report