本文介绍如何通过Node.js SDK快速调用API创建函数、调用函数等操作。

前提条件

您已完成以下操作:

Node.js SDK示例

示例代码如下:

'use strict';

var FCClient = require('@alicloud/fc2');

var client = new FCClient('<account id>', {
  accessKeyID: '<access key id>',
  accessKeySecret: '<access key secret>',
  region: 'cn-shanghai',
  timeout: 10000 // 请求超时时间(毫秒),默认为10s。
});

var serviceName = '<service name>';
var funcName = '<function name>';

client.createService(serviceName).then(function(resp) {
  console.log('create service: %j', resp);
  return client.createFunction(serviceName, {
    functionName: funcName,
    handler: 'index.handler',
    memorySize: 128,
    runtime: 'nodejs4.4',
    code: {
      zipFile: fs.readFileSync('/tmp/index.zip', 'base64'),
    },
  });
}).then(function(resp) {
  console.log('create function: %j', resp);
  return client.invokeFunction(serviceName, funcName, 'event');
}).then(function(resp) {
  console.log('invoke function: %j', resp);
}).catch(function(err) {
  console.error(err);
});

Node.js SDK异步调用示例

说明
  • 异步调用时,Node.js需是node 7.6或以上版本。
  • 关于异步调用的请求头,请参见Custom Headers

异步调用代码示例如下:

'use strict';

const FCClient = require('@alicloud/fc2');

var client = new FCClient('<account id>', {
  accessKeyID: '<access key id>',
  accessKeySecret: '<access key secret>',
  region: 'cn-shanghai',
});

var serviceName = '<service name>';
var funcName = '<function name>';

async function test () {
  try {
    var resp = await client.createService(serviceName);
    console.log('create service: %j', resp);

    resp = await client.createFunction(serviceName, {
      functionName: funcName,
      handler: 'counter.handler',
      memorySize: 128,
      runtime: 'nodejs4.4',
      initializer: 'counter.initializer',
      code: {
        zipFile: fs.readFileSync('/tmp/counter.zip', 'base64'),
      },
    });
    console.log('create function: %j', resp);

    // 缺省情况下,Resp解码为UTF-8。
    resp = await client.invokeFunction(serviceName, funcName, null);
    console.log('invoke function: %j', resp);

    // 如果在Opts中将rawBuf设置为True,则返回respWithBuf作为缓冲区。
    respWithBuf = await client.invokeFunction(serviceName, funcName, null, {}, 'LATEST', {rawBuf:true});

    uResp = await client.updateFunction(serviceName, funcName, {
      description: 'updated function desc',
      initializationTimeout: 60,
    });
    console.log('update function: %j', resp);
  } catch (err) {
    console.error(err);
  }
}
test().then();