

# 适用于 Node.js 金丝雀的库函数
<a name="Library_function_Nodejs"></a>

本节将介绍使用 Node.js 运行时可用于金丝雀脚本的库函数。

**Topics**
+ [addExecutionError(errorMessage, ex);](#Library_function_Nodejs_addExecutionError_Nodecanary)
+ [getCanaryName();](#Library_function_Nodejs_getCanaryName)
+ [getCanaryArn();](#Library_function_Nodejs_Nodecanary)
+ [getCanaryUserAgentString();](#Library_function_Nodejs_getCanaryUserAgentString_Nodecanary)
+ [getRuntimeVersion();](#Library_function_Nodejs_getRuntimeVersion_Nodecanary)
+ [getLogLevel();](#Library_function_Nodejs_getLogLevel_Nodecanary)
+ [setLogLevel();](#Library_function_Nodejs_setLogLevel_Nodecanary)
+ [executeStep(stepName, functionToExecute, [stepConfig])](#Library_function_Nodejs_executestep_Nodecanary)
+ [executeHttpStep(stepName, requestOptions, [callback], [stepConfig])](#Library_function_Nodejs_executeHttpStep)

## addExecutionError(errorMessage, ex);
<a name="Library_function_Nodejs_addExecutionError_Nodecanary"></a>

`errorMessage` 描述错误，`ex` 指遇到的异常

您可以使用 `addExecutionError` 来设置金丝雀的执行错误。它会在不中断脚本执行的情况下导致金丝雀失败。它也不会影响 `successPercent` 指标。

只有当错误对于指示金丝雀脚本成功或故障并不重要时，才应将错误作为执行错误进行跟踪。

以下是使用 `addExecutionError` 的示例。您将会监控端点的可用性，并在页面加载完成后捕获屏幕截图。由于捕获屏幕截图故障并不会决定端点的可用性，因此您可以捕获在截图时遇到的任何错误，并将它们添加为执行错误。可用性指标仍会指示端点已启动并正在运行，但金丝雀状态会被标记为失败。以下示例代码块将会捕获此类错误并将其添加为执行错误。

```
try {await synthetics.executeStep(stepName, callbackFunc);} catch(ex) {synthetics.addExecutionError('Unable to take screenshot ', ex);}
```

## getCanaryName();
<a name="Library_function_Nodejs_getCanaryName"></a>

返回金丝雀的名称。

## getCanaryArn();
<a name="Library_function_Nodejs_Nodecanary"></a>

返回金丝雀的 ARN。

## getCanaryUserAgentString();
<a name="Library_function_Nodejs_getCanaryUserAgentString_Nodecanary"></a>

返回金丝雀的自定义用户代理。

## getRuntimeVersion();
<a name="Library_function_Nodejs_getRuntimeVersion_Nodecanary"></a>

此函数在运行时版本 `syn-nodejs-3.0` 和更高版本中可用。其返回金丝雀的 Synthetics 运行时版本。例如，返回值可能为 `syn-nodejs-3.0`。

## getLogLevel();
<a name="Library_function_Nodejs_getLogLevel_Nodecanary"></a>

检索 Synthetics 库的当前日志级别。可能的值包括：
+ `0` – 调试
+ `1` – 信息
+ `2` – 警告
+ `3` – 错误

示例：

```
let logLevel = synthetics.getLogLevel();
```

## setLogLevel();
<a name="Library_function_Nodejs_setLogLevel_Nodecanary"></a>

设置 Synthetics 库的日志级别。可能的值包括：
+ `0` – 调试
+ `1` – 信息
+ `2` – 警告
+ `3` – 错误

示例：

```
synthetics.setLogLevel(0);
```

## executeStep(stepName, functionToExecute, [stepConfig])
<a name="Library_function_Nodejs_executestep_Nodecanary"></a>

执行提供的步骤，并使用开始/通过/失败日志记录，以及通过/失败和持续时间指标对其进行包装。

`executeStep` 函数还执行以下操作：
+ 记录步骤开始
+ 启动计时器
+ 执行提供的函数
+ 如果函数正常返回，则计为通过。如果函数引发异常，则计为失败
+ 结束计时器
+ 记录步骤是通过还是失败
+ 发出 `stepName SuccessPercent` 指标，100 表示通过，0 表示失败
+ 发出 `stepName Duration metric` 指标，其值基于步骤开始和结束时间
+ 返回 functionToExecute 返回的内容，或重新抛出 ` functionToExecute` 抛出的异常
+ 将步骤执行摘要添加到金丝雀的报告中

 **示例** 

```
await synthetics.executeStep(stepName, async function () {
    return new Promise((resolve, reject) => {
        const req = https.request(url, (res) => {
            console.log(`Status: ${res.statusCode}`);
            if (res.statusCode >= 400) {
                reject(new Error(`Request failed with status ${res.statusCode} for ${url}`));
            } else {
                resolve();
            }
        });

        req.on('error', (err) => {
            reject(new Error(`Request failed for ${url}: ${err.message}`));
        });

        req.end();
    });
});
```

## executeHttpStep(stepName, requestOptions, [callback], [stepConfig])
<a name="Library_function_Nodejs_executeHttpStep"></a>

作为步骤执行提供的 HTTP 请求，并发布 `SuccessPercent`（通过/失败）和 `Duration` 指标。

**executeHttpStep** 在后台使用 HTTP 或 HTTPS 本机函数，具体取决于请求中指定的协议。

此函数还将步骤执行摘要添加到金丝雀的报告中。摘要中包括有关每个 HTTP 请求的详细信息，如下所示：
+ 开始时间
+ 结束时间
+ 状态 (PASSED/FAILED)
+ 故障原因（如失败）
+ HTTP 调用详细信息，如请求/响应标头、请求/响应体、状态代码、状态消息和性能计时。

**Topics**
+ [参数](#Library_function_Nodejs_executeHttpStep_parameters_Nodecanary)
+ [executeHttpStep 的使用示例](#Library_function_Nodejs_executeHttpStep_examples_Nodecanary)

### 参数
<a name="Library_function_Nodejs_executeHttpStep_parameters_Nodecanary"></a>

 **stepName({{String}})** 

指定步骤的名称。此名称也用于发布此步骤的 CloudWatch 指标。

 **requestOptions({{Object or String}})** 

此参数的值可以是 URL、URL 字符串或对象。如果为对象，则必须是用以发出 HTTP 请求的一组可配置选项。其支持 Node.js 文档中 [http.request(options[, callback])](https://nodejs.org/api/http.html#http_http_request_options_callback) 中的所有选项。

除了这些 Node.js 选项之外，**requestOptions** 支持附加参数 `body`。您可以使用 `body` 参数将数据作为请求体传递。

 **callback({{response}})** 

（可选）此函数是与 HTTP 响应一起调用的用户函数。响应的类型为 [Class: http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)。

 **stepConfig({{object}})** 

（可选）使用此参数，可以用此步骤的不同配置覆盖全局 synthetics 配置。

### executeHttpStep 的使用示例
<a name="Library_function_Nodejs_executeHttpStep_examples_Nodecanary"></a>

以下一系列示例相互依存，以说明此选项的各种用途。

第一个示例展示配置请求参数。您可以将 URL 作为 **requestOptions** 传递：

```
let requestOptions = 'https://www.amazon.com';
```

或者，您也可以传递一组选项：

```
let requestOptions = {
        'hostname': 'myproductsEndpoint.com',
        'method': 'GET',
        'path': '/test/product/validProductName',
        'port': 443,
        'protocol': 'https:'
    };
```

在下一个示例中，创建一个接受响应的回调函数。预设情况下，如果您未指定 **callback**，CloudWatch Synthetics 会验证状态是否介于 200 和 299 之间（含）。

```
// Handle validation for positive scenario
    const callback = async function(res) {
        return new Promise((resolve, reject) => {
            if (res.statusCode < 200 || res.statusCode > 299) {
                throw res.statusCode + ' ' + res.statusMessage;
            }
     
            let responseBody = '';
            res.on('data', (d) => {
                responseBody += d;
            });
     
            res.on('end', () => {
                // Add validation on 'responseBody' here if required. For ex, your status code is 200 but data might be empty
                resolve();
            });
        });
    };
```

下一个示例展示为此步骤创建覆盖全局 CloudWatch Synthetics 配置的配置。在本示例中，步骤配置允许报告中包含请求标头、响应标头、请求体（发布数据）和响应体，并限制了“X-Amz-Security-Token”和“Authorization”标头值。预设情况下，出于安全原因，报告中不包括这些值。如果您选择将它们包含在报告中，则这些数据仅存储在 S3 存储桶中。

```
// By default headers, post data, and response body are not included in the report for security reasons. 
// Change the configuration at global level or add as step configuration for individual steps
let stepConfig = {
    includeRequestHeaders: true, 
    includeResponseHeaders: true,
    restrictedHeaders: ['X-Amz-Security-Token', 'Authorization'], // Restricted header values do not appear in report generated.
    includeRequestBody: true,
    includeResponseBody: true
};
```

最后一个例子展示将请求传递给 **executeHttpStep** 并对步骤命名。

```
await synthetics.executeHttpStep('Verify GET products API', requestOptions, callback, stepConfig);
```

在这组示例中，CloudWatch Synthetics 将每个步骤的详细信息添加在报告中，并使用 **stepName** 生成每个步骤的指标。

 您将看到 `Verify GET products API` 步骤的 `successPercent` 和 `duration` 指标。您可以通过监控 API 调用步骤的指标来监控 API 性能。

有关使用这些函数的完整脚本示例，请参阅 [多步骤 API 金丝雀](CloudWatch_Synthetics_Canaries_Samples.md#CloudWatch_Synthetics_Canaries_Samples_APIsteps)。