

# 适用于 CloudFront Functions 的 JavaScript 运行时 1.0 功能
<a name="functions-javascript-runtime-10"></a>

CloudFront Functions JavaScript 运行时环境符合 [ECMAScript (ES) 版本 5.1](https://262.ecma-international.org/5.1/)，也支持 ES 版本 6 至 9 的某些功能。它还提供了一些不属于 ES 规范的非标准方法。

以下主题列出了所有支持的语言功能。

**Topics**
+ [核心功能](#writing-functions-javascript-features-core)
+ [原语对象](#writing-functions-javascript-features-primitive-objects)
+ [内置对象](#writing-functions-javascript-features-builtin-objects)
+ [错误类型](#writing-functions-javascript-features-error-types)
+ [全局变量](#writing-functions-javascript-features-globals)
+ [内置模块](#writing-functions-javascript-features-builtin-modules)
+ [受限功能](#writing-functions-javascript-features-restricted-features)

## 核心功能
<a name="writing-functions-javascript-features-core"></a>

支持 ES 的以下核心功能。

**类型**  
支持所有 ES 5.1 类型。这包括布尔值、数字、字符串、对象、数组、函数、函数构造函数和正则表达式。

**运算符**  
支持所有 ES 5.1 运算符。  
支持 ES 7 幂运算符 (`**`)。

**语句**  
不支持 `const` 和 `let` 语句。
支持以下 ES 5.1 语句：  
+ `break`
+ `catch`
+ `continue`
+ `do-while`
+ `else`
+ `finally`
+ `for`
+ `for-in`
+ `if`
+ `return`
+ `switch`
+ `throw`
+ `try`
+ `var`
+ `while`
+ 带标签的语句

**文本**  
支持 ES 6 模板文本：多行字符串、表达式插值和嵌套模板。

**函数**  
支持所有的 ES 5.1 函数功能。  
支持 ES 6 箭头函数，并支持 ES 6 rest 参数语法。

**Unicode**  
源文本和字符串文本可以包含 Unicode 编码的字符。还支持由六个字符组成的 Unicode 代码点转义序列（例如，`\uXXXX`）。

**严格模式**  
默认情况下，函数在严格模式下运行，因此您无需在函数代码中添加 `use strict` 语句。无法对其进行更改。

## 原语对象
<a name="writing-functions-javascript-features-primitive-objects"></a>

支持 ES 的以下原语对象。

**对象**  
支持对对象使用以下 ES 5.1 方法：  
+ `create`（没有属性列表）
+ `defineProperties`
+ `defineProperty`
+ `freeze`
+ `getOwnPropertyDescriptor`
+ `getOwnPropertyNames`
+ `getPrototypeOf`
+ `hasOwnProperty`
+ `isExtensible`
+ `isFrozen`
+ `prototype.isPrototypeOf`
+ `isSealed`
+ `keys`
+ `preventExtensions`
+ `prototype.propertyIsEnumerable`
+ `seal`
+ `prototype.toString`
+ `prototype.valueOf`
支持对对象使用以下 ES 6 方法：  
+ `assign`
+ `is`
+ `prototype.setPrototypeOf`
支持对对象使用以下 ES 8 方法：  
+ `entries`
+ `values`

**字符串**  
支持对字符串使用以下 ES 5.1 方法：  
+ `fromCharCode`
+ `prototype.charAt`
+ `prototype.concat`
+ `prototype.indexOf`
+ `prototype.lastIndexOf`
+ `prototype.match`
+ `prototype.replace`
+ `prototype.search`
+ `prototype.slice`
+ `prototype.split`
+ `prototype.substr`
+ `prototype.substring`
+ `prototype.toLowerCase`
+ `prototype.trim`
+ `prototype.toUpperCase`
支持对字符串使用以下 ES 6 方法：  
+ `fromCodePoint`
+ `prototype.codePointAt`
+ `prototype.endsWith`
+ `prototype.includes`
+ `prototype.repeat`
+ `prototype.startsWith`
支持对字符串使用以下 ES 8 方法：  
+ `prototype.padStart`
+ `prototype.padEnd`
支持对字符串使用以下 ES 9 方法：  
+ `prototype.trimStart`
+ `prototype.trimEnd`
支持对字符串使用以下非标准方法：  
+ `prototype.bytesFrom(array | string, encoding)`

  从八位数组或编码字符串创建字节字符串。字符串编码选项为 `hex`、`base64` 和 `base64url`。
+ `prototype.fromBytes(start[, end])`

  从字节字符串创建 Unicode 字符串，其中每个字节都被替换为相应的 Unicode 代码点。
+ `prototype.fromUTF8(start[, end])`

  从 UTF-8 编码的字节字符串创建 Unicode 字符串。如果编码不正确，则会返回 `null`。
+ `prototype.toBytes(start[, end])`

  从 Unicode 字符串创建字节字符串。所有字符都必须在 [0,255] 范围内。如果不在该范围内，它会返回 `null`。
+ `prototype.toUTF8(start[, end])`

  从 Unicode 字符串创建 UTF-8 编码的字节字符串。

**数字**  
支持对数字使用所有 ES 5.1 方法。  
支持对数字使用以下 ES 6 方法：  
+ `isFinite`
+ `isInteger`
+ `isNaN`
+ `isSafeInteger`
+ `parseFloat`
+ `parseInt`
+ `prototype.toExponential`
+ `prototype.toFixed`
+ `prototype.toPrecision`
+ `EPSILON`
+ `MAX_SAFE_INTEGER`
+ `MAX_VALUE`
+ `MIN_SAFE_INTEGER`
+ `MIN_VALUE`
+ `NEGATIVE_INFINITY`
+ `NaN`
+ `POSITIVE_INFINITY`

## 内置对象
<a name="writing-functions-javascript-features-builtin-objects"></a>

支持 ES 的以下内置对象。

**数学**  
支持所有 ES 5.1 数学方法。  
在 CloudFront Functions 运行时环境中，`Math.random()` 实现使用植入有函数运行时间戳的 OpenBSD `arc4random`。
支持以下 ES 6 数学方法：  
+ `acosh`
+ `asinh`
+ `atanh`
+ `cbrt`
+ `clz32`
+ `cosh`
+ `expm1`
+ `fround`
+ `hypot`
+ `imul`
+ `log10`
+ `log1p`
+ `log2`
+ `sign`
+ `sinh`
+ `tanh`
+ `trunc`
+ `E`
+ `LN10`
+ `LN2`
+ `LOG10E`
+ `LOG2E`
+ `PI`
+ `SQRT1_2`
+ `SQRT2`

**日期**  
支持所有 ES 5.1 `Date` 功能。  
出于安全原因，在单个函数运行的生命周期内，`Date` 始终返回相同的值（函数的开始时间）。有关更多信息，请参阅 [受限功能](#writing-functions-javascript-features-restricted-features)。

**函数**  
支持 `apply`、`bind` 和 `call` 方法。  
不支持函数构造函数。

**正则表达式**  
支持所有 ES 5.1 正则表达式功能。正则表达式语言与 Perl 兼容。支持 ES 9 命名的捕获组。

**JSON**  
支持所有 ES 5.1 JSON 功能，包括 `parse` 和 `stringify`。

**数组**  
支持对数组使用以下 ES 5.1 方法：  
+ `isArray`
+ `prototype.concat`
+ `prototype.every`
+ `prototype.filter`
+ `prototype.forEach`
+ `prototype.indexOf`
+ `prototype.join`
+ `prototype.lastIndexOf`
+ `prototype.map`
+ `prototype.pop`
+ `prototype.push`
+ `prototype.reduce`
+ `prototype.reduceRight`
+ `prototype.reverse`
+ `prototype.shift`
+ `prototype.slice`
+ `prototype.some`
+ `prototype.sort`
+ `prototype.splice`
+ `prototype.unshift`
支持对数组使用以下 ES 6 方法：  
+ `of`
+ `prototype.copyWithin`
+ `prototype.fill`
+ `prototype.find`
+ `prototype.findIndex`
支持对数组使用以下 ES 7 方法：  
+ `prototype.includes`

**类型化数组**  
支持对数组使用以下 ES 6 类型化数组：  
+ `Int8Array`
+ `Uint8Array`
+ `Uint8ClampedArray`
+ `Int16Array`
+ `Uint16Array`
+ `Int32Array`
+ `Uint32Array`
+ `Float32Array`
+ `Float64Array`
+ `prototype.copyWithin`
+ `prototype.fill`
+ `prototype.join`
+ `prototype.set`
+ `prototype.slice`
+ `prototype.subarray`
+ `prototype.toString`

**ArrayBuffer**  
支持对 `ArrayBuffer` 使用以下方法：  
+ `prototype.isView`
+ `prototype.slice`

**Promise**  
支持以下承诺方法：  
+ `reject`
+ `resolve`
+ `prototype.catch`
+ `prototype.finally`
+ `prototype.then`

**加密**  
加密模块提供标准哈希和基于哈希的消息身份验证码 (HMAC) 帮助程序。您可以使用 `require('crypto')` 加载模块。该模块公开了以下方法，这些方法的行为与 Node.js 对应方法完全相同：  
+ `createHash(algorithm)`
+ `hash.update(data)`
+ `hash.digest([encoding])`
+ `createHmac(algorithm, secret key)`
+ `hmac.update(data)`
+ `hmac.digest([encoding])`
有关更多信息，请参阅内置模块部分中的 [加密（哈希和 HMAC）](#writing-functions-javascript-features-builtin-modules-crypto)。

**控制台**  
这是调试的帮助对象。它只支持 `log()` 方法来记录日志消息。  
CloudFront Functions 不支持逗号语法，例如 `console.log('a', 'b')`。改为使用 `console.log('a' + ' ' + 'b')` 格式。

## 错误类型
<a name="writing-functions-javascript-features-error-types"></a>

支持以下错误对象：
+ `Error`
+ `EvalError`
+ `InternalError`
+ `MemoryError`
+ `RangeError`
+ `ReferenceError`
+ `SyntaxError`
+ `TypeError`
+ `URIError`

## 全局变量
<a name="writing-functions-javascript-features-globals"></a>

支持 `globalThis` 对象。

支持以下 ES 5.1 全局函数：
+ `decodeURI`
+ `decodeURIComponent`
+ `encodeURI`
+ `encodeURIComponent`
+ `isFinite`
+ `isNaN`
+ `parseFloat`
+ `parseInt`

支持以下全局常数：
+ `NaN`
+ `Infinity`
+ `undefined`

## 内置模块
<a name="writing-functions-javascript-features-builtin-modules"></a>

支持以下内置模块。

**Topics**
+ [加密（哈希和 HMAC）](#writing-functions-javascript-features-builtin-modules-crypto)
+ [查询字符串](#writing-functions-javascript-features-builtin-modules-query-string)

### 加密（哈希和 HMAC）
<a name="writing-functions-javascript-features-builtin-modules-crypto"></a>

加密模块 (`crypto`) 提供标准哈希和基于哈希的消息身份验证码 (HMAC) 帮助程序。您可以使用 `require('crypto')` 加载模块。该模块提供了以下方法，这些方法的行为与 Node.js 对应方法完全相同：

**哈希方法**

`crypto.createHash(algorithm)`  
创建并返回哈希对象，您可以使用给定的算法：`md5`、`sha1` 或 `sha256` 通过它生成哈希摘要。

`hash.update(data)`  
用给定的 `data` 更新哈希内容。

`hash.digest([encoding])`  
计算使用 `hash.update()` 传递的所有数据的摘要。编码可以是 `hex`、`base64` 或 `base64url`。

**HMAC 方法**

`crypto.createHmac(algorithm, secret key)`  
创建并返回使用给定的 `algorithm` 和 `secret key` 的 HMAC 对象。算法可以是 `md5`、`sha1` 或 `sha256`。

`hmac.update(data)`  
用给定的 `data` 更新 HMAC 内容。

`hmac.digest([encoding])`  
计算使用 `hmac.update()` 传递的所有数据的摘要。编码可以是 `hex`、`base64` 或 `base64url`。

### 查询字符串
<a name="writing-functions-javascript-features-builtin-modules-query-string"></a>

**注意**  
[CloudFront Functions 事件对象](functions-event-structure.md)自动为您解析 URL 查询字符串。这意味着，在大多数情况下您不需要使用此模块。

查询字符串模块 (`querystring`) 提供了解析和格式化 URL 查询字符串的方法。您可以使用 `require('querystring')` 加载模块。该模块提供了以下方法。

`querystring.escape(string)`  
URL - 对给定的 `string` 进行编码，从而返回转义的查询字符串。该方法由 `querystring.stringify()` 使用，不应直接使用。

`querystring.parse(string[, separator[, equal[, options]]])`  
解析查询字符串 (`string`) 并返回对象。  
`separator` 参数是用于在查询字符串中分隔键和值对的子字符串。默认为 `&`。  
`equal` 参数是用于在查询字符串中分隔键和值的子字符串。默认为 `=`。  
`options` 参数是具有以下键的对象：    
`decodeURIComponent function`  
用于解码查询字符串中百分比编码字符的函数。默认为 `querystring.unescape()`。  
`maxKeys number`  
要解析的最大密钥数。默认为 `1000`。使用 `0` 的值取消键的计数限制。
默认情况下，假定查询字符串中的百分比编码字符使用 UTF-8 编码。无效的 UTF-8 序列将被替换为 `U+FFFD` 替换字符。  
例如，对于以下查询字符串：  

```
'name=value&abc=xyz&abc=123'
```
`querystring.parse()` 的返回值为：  

```
{
name: 'value',
abc: ['xyz', '123']
}
```
`querystring.decode()` 是 `querystring.parse()` 的别名。

`querystring.stringify(object[, separator[, equal[, options]]])`  
序列化 `object` 并返回查询字符串。  
`separator` 参数是用于在查询字符串中分隔键和值对的子字符串。默认为 `&`。  
`equal` 参数是用于在查询字符串中分隔键和值的子字符串。默认为 `=`。  
`options` 参数是具有以下键的对象：    
`encodeURIComponent function`  
用于将 URL 不安全字符转换为查询字符串中的百分比编码的函数。默认为 `querystring.escape()`。
默认情况下，查询字符串中需要百分比编码的字符将编码为 UTF-8。要使用其他编码，请指定 `encodeURIComponent` 选项。  
例如，在下面的代码中：  

```
querystring.stringify({ name: 'value', abc: ['xyz', '123'], anotherName: '' });
```
返回值为：  

```
'name=value&abc=xyz&abc=123&anotherName='
```
`querystring.encode()` 是 `querystring.stringify()` 的别名。

`querystring.unescape(string)`  
对给定的 `string` 中的 URL 百分比编码字符进行解码，以返回未转义的查询字符串。此方法由 `querystring.parse()` 使用，不应直接使用。

## 受限功能
<a name="writing-functions-javascript-features-restricted-features"></a>

由于安全考虑，以下 JavaScript 语言功能或不受支持，或收到限制。

**动态代码评估**  
不支持动态代码评估。如果尝试，`eval()` 和 `Function` 构造函数都会引发错误。例如，`const sum = new Function('a', 'b', 'return a + b')` 引发错误。

**计时器**  
不支持 `setTimeout()`、`setImmediate()` 和 `clearTimeout()` 函数。在函数运行中没有可以推迟或生成的预置。您的函数必须同步运行才能完成。

**日期和时间戳**  
出于安全原因，无法访问高分辨率计时器。在单个函数运行的生命周期内，查询当前时间的所有 `Date` 方法始终返回相同的值。返回的时间戳是函数开始运行的时间。因此，您无法度量函数中的经过时间。

**文件系统访问**  
没有文件系统访问权限。例如，没有像 Node.js 的 `fs` 模块可以进行文件系统访问。

**处理访问权限**  
没有处理访问权限。例如，没有像 Node.js 中那样用于处理信息访问权限的 `process` 全局对象。

**环境变量**  
无法访问环境变量。  
相反，可以使用 CloudFront KeyValueStore 为 CloudFront Functions 创建集中式的键值对数据存储。借助 CloudFront KeyValueStore，无需部署代码更改即对配置数据进行动态更新。必须使用 [JavaScript 运行时 2.0](functions-javascript-runtime-20.md) 才能使用 CloudFront KeyValueStore。有关更多信息，请参阅 [Amazon CloudFront KeyValueStore](kvs-with-functions.md)。

**网络访问**  
不支持网络调用。例如，不支持 XHR、HTTP (S) 和套接字。