Node.js
更新时间:2024-07-05
本示例演示用 Node.js SDK 创建和执行您的 CFC 函数。
安装
推荐使用 npm 来安装。在终端输入如下命令:
Bash
1npm install @baiducloud/sdk --save
使用样例
Plain Text
1var CfcClient =require('@baiducloud/sdk').CfcClient;
2
3config = {
4 endpoint: '<you endpoint>',
5 credentials: {
6 ak: '<Your ak>',
7 sk: '<Your sk>'
8 }
9};
10/*
11还可以使用从环境变量中读取ak,sk的方式
12config = {
13 endpoint: '<you endpoint>',
14 credentials: {
15 ak: process.env.BCE_ACCESS_KEY_ID,
16 sk: process.env.BCE_ACCESS_KEY_SECRET
17 }
18}
19*/
20
21//创建cfc客服端
22var client = new CfcClient(config);
23
24var body = {
25 'Code': {
26 'ZipFile': '<Your base64-encoded Code>',
27 'Publish': false,
28 },
29 'Description': 'CFC SDK Demo',
30 'Region': 'bj',
31 'Timeout': 3,
32 'FunctionName': 'testHelloWorld',
33 'Handler': '<your index>.handler',
34 'Runtime': 'nodejs6.11',
35 'MemorySize': 128,
36 'Environment': {
37 'Variables': {
38 'a': 'b',
39 }
40 }
41};
42
43var invokeBody = {
44 'key3': 'value3',
45 'key2': 'value2',
46 'key1': 'value1'
47};
48
49var invokeOptions = {
50 'logToBody': 'false',
51 'invocationType': 'RequestResponse',
52 'logType': 'None',
53 'Qualifier': '$LATEST'
54};
55
56client.createFunction(body).then(function (response) {
57 // 创建函数成功
58 console.log('create function:',response.body);
59 return response;
60}).then(function (response) {
61 // 执行函数
62 return client.invocations(response.body.FunctionBrn, invokeBody, invokeOptions);
63}).then(function (response) {
64 // 执行函数成功
65 console.log('invocation result:', response.body);
66}).catch(function (err) {
67 // 执行失败
68 console.error('error:', err);
69});