Azure Functions JavaScript 开发人员指南Azure Functions JavaScript developer guide

本指南包含有助于成功使用 JavaScript 开发 Azure Functions 的详细信息。This guide contains detailed information to help you succeed developing Azure Functions using JavaScript.

作为 Express.js、Node.js 或 JavaScript 开发人员,如果不熟悉 Azure Functions,请考虑先阅读以下文章之一:As an Express.js, Node.js, or JavaScript developer, if you are new to Azure Functions, please consider first reading one of the following articles:

入门Getting started 概念Concepts 指导式学习Guided learning

JavaScript 函数基础知识JavaScript function basics

JavaScript (Node.js) 函数是导出的 function,它在触发时执行(触发器在 function.json 中配置)。A JavaScript (Node.js) function is an exported function that executes when triggered (triggers are configured in function.json). 传递给每个函数的第一个参数是 context 对象,该对象用于接收和发送绑定数据、日志记录以及与运行时通信。The first argument passed to every function is a context object, which is used for receiving and sending binding data, logging, and communicating with the runtime.

文件夹结构Folder structure

JavaScript 项目所需的文件夹结构如下所示。The required folder structure for a JavaScript project looks like the following. 可更改此默认值。This default can be changed. 有关详细信息,请参阅下面的 scriptFile 部分。For more information, see the scriptFile section below.

 | - MyFirstFunction
 | | - index.js
 | | - function.json
 | - MySecondFunction
 | | - index.js
 | | - function.json
 | - SharedCode
 | | - myFirstHelperFunction.js
 | | - mySecondHelperFunction.js
 | - node_modules
 | - host.json
 | - package.json
 | - extensions.csproj

项目的根目录中有共享的 host.json 文件,可用于配置函数应用。At the root of the project, there's a shared host.json file that can be used to configure the function app. 每个函数都具有一个文件夹,其中包含其代码文件 (.js) 和绑定配置文件 (function.json)。Each function has a folder with its own code file (.js) and binding configuration file (function.json). function.json 父目录的名称始终是函数的名称。The name of function.json's parent directory is always the name of your function.

2.x 版 Functions 运行时中所需的绑定扩展在 extensions.csproj 文件中定义,实际库文件位于 bin 文件夹中。The binding extensions required in version 2.x of the Functions runtime are defined in the extensions.csproj file, with the actual library files in the bin folder. 本地开发时,必须注册绑定扩展When developing locally, you must register binding extensions. 在 Azure 门户中开发函数时,系统将为你完成此注册。When developing functions in the Azure portal, this registration is done for you.

导出函数Exporting a function

必须通过 module.exports(或 exports)导出 JavaScript 函数。JavaScript functions must be exported via module.exports (or exports). 导出的函数应是触发时执行的 JavaScript 函数。Your exported function should be a JavaScript function that executes when triggered.

默认情况下,Functions 运行时会在 index.js 中查找你的函数,其中,index.js 与其相应的 function.json 共享同一个父目录。By default, the Functions runtime looks for your function in index.js, where index.js shares the same parent directory as its corresponding function.json. 默认情况下,导出的函数应该是其文件中的唯一导出,或者名为 runindex 的导出。In the default case, your exported function should be the only export from its file or the export named run or index. 若要配置文件位置和导出函数名称,请阅读下面的配置函数的入口点To configure the file location and export name of your function, read about configuring your function's entry point below.

在执行时,将为导出的函数传递一些参数。Your exported function is passed a number of arguments on execution. 采用的第一个参数始终是 context 对象。The first argument it takes is always a context object. 如果函数是同步的(不返回 Promise),则必须传递 context 对象,因为需要调用 context.done 才能正常使用该函数。If your function is synchronous (doesn't return a Promise), you must pass the context object, as calling context.done is required for correct use.

// You should include context, other arguments are optional
module.exports = function(context, myTrigger, myInput, myOtherInput) {
    // function logic goes here :)

导出异步函数Exporting an async function

在 Functions 运行时版本 2.x 中使用 async function 声明或普通 JavaScript Promise,无需显式调用 context.done 回调即可通知函数已完成。When using the async function declaration or plain JavaScript Promises in version 2.x of the Functions runtime, you do not need to explicitly call the context.done callback to signal that your function has completed. 导出的异步函数/Promise 完成时,函数将完成。Your function completes when the exported async function/Promise completes. 对于面向版本 1.x 运行时的函数,在代码完成执行后,仍必须调用 context.doneFor functions targeting the version 1.x runtime, you must still call context.done when your code is done executing.

以下示例是一个简单的函数,用于记录其已被触发并立即完成执行。The following example is a simple function that logs that it was triggered and immediately completes execution.

module.exports = async function (context) {
    context.log('JavaScript trigger function processed a request.');

导出异步函数时,还可配置输出绑定,以使用 return 值。When exporting an async function, you can also configure an output binding to take the return value. 如果只有一个输出绑定,则建议使用此值。This is recommended if you only have one output binding.

若要使用 return 分配输出,请在 function.json 中将 name 属性更改为 $returnTo assign an output using return, change the name property to $return in function.json.

  "type": "http",
  "direction": "out",
  "name": "$return"

在这种情况下,函数应如以下示例所示:In this case, your function should look like the following example:

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    // You can call and await an async method here
    return {
        body: "Hello, world!"


在 JavaScript 中,需在函数的 function.json 中配置和定义绑定In JavaScript, bindings are configured and defined in a function's function.json. 函数通过多种方式来与绑定交互。Functions interact with bindings a number of ways.


在 Azure Functions 中,输入分为两种类别:一种是触发器输入,另一种则是附加输入。Input are divided into two categories in Azure Functions: one is the trigger input and the other is the additional input. 函数可通过三种方式读取触发器和其他输入绑定(direction === "in" 的绑定):Trigger and other input bindings (bindings of direction === "in") can be read by a function in three ways:

  • [建议] 以传递给函数的参数的形式。[Recommended] As parameters passed to your function. 它们以与 function.json 中定义的顺序相同的顺序传递给函数。They are passed to the function in the same order that they are defined in function.json. function.json 中定义的 name 属性不需要与参数名称匹配,不过两者应该匹配。The name property defined in function.json does not need to match the name of your parameter, although it should.

    module.exports = async function(context, myTrigger, myInput, myOtherInput) { ... };
  • context.bindings 对象的成员的形式。As members of the context.bindings object. 每个成员由 function.json 中定义的 name 属性命名。Each member is named by the name property defined in function.json.

    module.exports = async function(context) { 
        context.log("This is myTrigger: " + context.bindings.myTrigger);
        context.log("This is myInput: " + context.bindings.myInput);
        context.log("This is myOtherInput: " + context.bindings.myOtherInput);
  • 使用 JavaScript arguments 对象以输入的形式。As inputs using the JavaScript arguments object. 这实质上与作为参数传递输入相同,但可以动态处理输入。This is essentially the same as passing inputs as parameters, but allows you to dynamically handle inputs.

    module.exports = async function(context) { 
        context.log("This is myTrigger: " + arguments[1]);
        context.log("This is myInput: " + arguments[2]);
        context.log("This is myOtherInput: " + arguments[3]);


函数可通过多种方式写入输出(direction === "out" 的绑定)。Outputs (bindings of direction === "out") can be written to by a function in a number of ways. 在所有情况下,function.json 中定义的绑定属性 name 对应于函数中所写入到的对象成员的名称。In all cases, the name property of the binding as defined in function.json corresponds to the name of the object member written to in your function.

可通过以下方式之一将数据分配到输出绑定(不要结合使用这些方法):You can assign data to output bindings in one of the following ways (don't combine these methods):

  • [有多个输出时建议使用] 返回对象。[Recommended for multiple outputs] Returning an object. 如果使用异步函数/返回 Promise 的函数,可以返回分配有输出数据的对象。If you are using an async/Promise returning function, you can return an object with assigned output data. 在以下示例中,function.json 中的输出绑定名为“httpResponse”和“queueOutput”。In the example below, the output bindings are named "httpResponse" and "queueOutput" in function.json.

    module.exports = async function(context) {
        let retMsg = 'Hello, world!';
        return {
            httpResponse: {
                body: retMsg
            queueOutput: retMsg

    如果使用同步函数,可以使用 context.done 返回此对象(请参阅示例)。If you are using a synchronous function, you can return this object using context.done (see example).

  • [有单个输出时建议使用] 直接返回值,并使用 $return 绑定名称。[Recommended for single output] Returning a value directly and using the $return binding name. 这仅适用于异步函数/返回 Promise 的函数。This only works for async/Promise returning functions. 请参阅导出异步函数中的示例。See example in exporting an async function.

  • context.bindings 赋值 可以直接向 context.bindings 赋值。Assigning values to context.bindings You can assign values directly to context.bindings.

    module.exports = async function(context) {
        let retMsg = 'Hello, world!';
        context.bindings.httpResponse = {
            body: retMsg
        context.bindings.queueOutput = retMsg;

绑定数据类型Bindings data type

若要定义输入绑定的数据类型,请使用绑定定义中的 dataType 属性。To define the data type for an input binding, use the dataType property in the binding definition. 例如,若要以二进制格式读取 HTTP 请求的内容,请使用类型 binaryFor example, to read the content of an HTTP request in binary format, use the type binary:

    "type": "httpTrigger",
    "name": "req",
    "direction": "in",
    "dataType": "binary"

dataType 的选项为 binarystreamstringOptions for dataType are: binary, stream, and string.

上下文对象context object

运行时使用 context 对象将数据传入和传出函数和运行时。The runtime uses a context object to pass data to and from your function and the runtime. context 对象用于从绑定读取和设置数据并用于写入日志,它始终是传递到函数的第一个参数。Used to read and set data from bindings and for writing to logs, the context object is always the first parameter passed to a function.

对于具有同步代码的函数,上下文对象包括在函数完成处理时调用的 done 回叫。For functions featuring synchronous code, the context object includes the done callback which you call when the function is done processing. 编写异步代码时,无需显式调用 donedone 回叫是隐式调用的。Explicitly calling done is unnecessary when writing asynchronous code; the done callback is called implicitly.

module.exports = (context) => {

    // function logic goes here

    context.log("The function has executed.");


传递到函数的上下文公开了一个 executionContext 属性,该属性是一个具有以下属性的对象:The context passed into your function exposes an executionContext property, which is an object with the following properties:

属性名称Property name 类型Type 说明Description
invocationId StringString 提供特定函数调用的唯一标识符。Provides a unique identifier for the specific function invocation.
functionName StringString 提供正在运行的函数的名称Provides the name of the running function
functionDirectory StringString 提供函数应用目录。Provides the functions app directory.

以下示例演示如何返回 invocationIdThe following example shows how to return the invocationId.

module.exports = (context, req) => {
    context.res = {
        body: context.executionContext.invocationId

context.bindings 属性context.bindings property


返回用于读取或分配绑定数据的命名对象。Returns a named object that is used to read or assign binding data. 可以通过读取 context.bindings 上的属性来访问输入和触发器绑定数据。Input and trigger binding data can be accessed by reading properties on context.bindings. 可以通过将数据添加到 context.bindings 来分配输出绑定数据Output binding data can be assigned by adding data to context.bindings

例如,function.json 中的以下绑定定义允许通过 context.bindings.myInput 访问队列的内容和使用 context.bindings.myOutput 将输出分配给队列。For example, the following binding definitions in your function.json let you access the contents of a queue from context.bindings.myInput and assign outputs to a queue using context.bindings.myOutput.

// myInput contains the input data, which may have properties such as "name"
var author =;
// Similarly, you can set your output data
context.bindings.myOutput = { 
        some_text: 'hello world', 
        a_number: 1 };

可以选择使用 context.done 方法而不是 context.binding 对象来定义输出绑定数据(参阅下文)。You can choose to define output binding data using the context.done method instead of the context.binding object (see below).

context.bindingData 属性context.bindingData property


返回包含触发器元数据和函数调用数据(invocationIdsys.methodNamesys.utcNowsys.randGuid)的命名对象。Returns a named object that contains trigger metadata and function invocation data (invocationId, sys.methodName, sys.utcNow, sys.randGuid). 有关触发器元数据的示例,请参阅此事件中心示例For an example of trigger metadata, see this event hubs example.

context.done 方法context.done method


让运行时知道代码已完成。Lets the runtime know that your code has completed. 如果函数使用 async function 声明,则你不需要使用 context.done()When your function uses the async function declaration, you do not need to use context.done(). context.done 回调是隐式调用的。The context.done callback is implicitly called. 异步函数在 Node 8 或更高版本(需要 Functions 运行时版本 2.x)中可用。Async functions are available in Node 8 or a later version, which requires version 2.x of the Functions runtime.

如果函数不是异步函数,则必须调用 context.done 来告知运行时函数是完整的。If your function is not an async function, you must call context.done to inform the runtime that your function is complete. 如果缺少它,则执行将会超时。The execution times out if it is missing.

使用 context.done 方法可向运行时传回用户定义的错误,以及传回包含输出绑定数据的 JSON 对象。The context.done method allows you to pass back both a user-defined error to the runtime and a JSON object containing output binding data. 传递给 context.done 的属性将覆盖 context.bindings 对象上设置的任何内容。Properties passed to context.done overwrite anything set on the context.bindings object.

// Even though we set myOutput to have:
//  -> text: 'hello world', number: 123
context.bindings.myOutput = { text: 'hello world', number: 123 };
// If we pass an object to the done function...
context.done(null, { myOutput: { text: 'hello there, world', noNumber: true }});
// the done method overwrites the myOutput binding to be: 
//  -> text: 'hello there, world', noNumber: true

context.log 方法context.log method


利用该方法,可以在其他日志记录级别可用的情况下在默认跟踪级别写入到流式处理函数日志。Allows you to write to the streaming function logs at the default trace level, with other logging levels available. 在下一部分中会详细说明跟踪日志记录。Trace logging is described in detail in the next section.

将跟踪输出写入到日志Write trace output to logs

在 Functions 中,可使用 context.log 方法将跟踪输出写入到日志和控制台。In Functions, you use the context.log methods to write trace output to the logs and the console. 在调用 context.log() 时,消息会在默认跟踪级别(即,信息跟踪级别)写入到日志。When you call context.log(), your message is written to the logs at the default trace level, which is the info trace level. Functions 与 Azure Application Insights 集成,从而能够更好地捕获函数应用日志。Functions integrates with Azure Application Insights to better capture your function app logs. Application Insights 是 Azure Monitor 的一部分,它提供了对应用程序遥测数据和跟踪输出都可以进行收集、视觉呈现和分析的工具。Application Insights, part of Azure Monitor, provides facilities for collection, visual rendering, and analysis of both application telemetry and your trace outputs. 若要了解详细信息,请参阅监视 Azure FunctionsTo learn more, see monitoring Azure Functions.

下面的示例在信息跟踪级别写入日志,包括调用 ID:The following example writes a log at the info trace level, including the invocation ID:

context.log("Something has happened. " + context.invocationId); 

所有 context.log 方法都支持 Node.js util.format 方法支持的同一参数格式。All context.log methods support the same parameter format that's supported by the Node.js util.format method. 请考虑以下代码,它使用默认跟踪级别写入函数日志:Consider the following code, which writes function logs by using the default trace level:

context.log('Node.js HTTP trigger function processed a request. RequestUri=' + req.originalUrl);
context.log('Request Headers = ' + JSON.stringify(req.headers));

还可以采用以下格式编写同一代码:You can also write the same code in the following format:

context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl);
context.log('Request Headers = ', JSON.stringify(req.headers));


请勿使用 console.log 来写入跟踪输出。Don't use console.log to write trace outputs. 因为 console.log 的输出是在函数应用级别捕获的,所以它不会绑定到特定的函数调用,并且不会显示在特定函数的日志中。Because output from console.log is captured at the function app level, it's not tied to a specific function invocation and isn't displayed in a specific function's logs. 此外,Functions 运行时的 1.x 版本不支持使用 console.log 写入到控制台。Also, version 1.x of the Functions runtime doesn't support using console.log to write to the console.

跟踪级别Trace levels

除了默认级别外,通过使用以下日志记录方法还可以在特定的跟踪级别写入函数日志。In addition to the default level, the following logging methods are available that let you write function logs at specific trace levels.

方法Method 说明Description
error(message)error(message) 将错误级别的事件写入到日志。Writes an error-level event to the logs.
warn(message)warn(message) 将警告级别的事件写入到日志。Writes a warning-level event to the logs.
info(message)info(message) 向信息级日志记录或更低级别进行写入。Writes to info level logging, or lower.
verbose(message)verbose(message) 向详细级日志记录进行写入。Writes to verbose level logging.

以下示例在警告跟踪级别(而不是信息级别)写入同一个日志:The following example writes the same log at the warning trace level, instead of the info level:

context.log.warn("Something has happened. " + context.invocationId); 

因为 错误 是最高跟踪级别,所以,只要启用了日志记录,此跟踪会在所有跟踪级别写入到输出中。Because error is the highest trace level, this trace is written to the output at all trace levels as long as logging is enabled.

配置跟踪级别以便进行日志记录Configure the trace level for logging

利用 Functions,可以定义阈值跟踪级别以便写入到日志或控制台。Functions lets you define the threshold trace level for writing to the logs or the console. 特定的阈值设置取决于 Functions 运行时的版本。The specific threshold settings depend on your version of the Functions runtime.

若要为写入到日志的跟踪设置阈值,请在 host.json 文件中使用 logging.logLevel 属性。To set the threshold for traces written to the logs, use the logging.logLevel property in the host.json file. 利用此 JSON 对象,可以为函数应用中的所有函数定义默认阈值,另外还可以为单个函数定义特定阈值。This JSON object lets you define a default threshold for all functions in your function app, plus you can define specific thresholds for individual functions. 若要了解详细信息,请参阅如何配置对 Azure Functions 的监视To learn more, see How to configure monitoring for Azure Functions.

记录自定义遥测数据Log custom telemetry

默认情况下,Functions 将输出作为跟踪写入到 Application Insights。By default, Functions writes output as traces to Application Insights. 为了加强控制,可以改用 Application Insights Node.js SDK 将自定义遥测数据发送到 Application Insights 实例。For more control, you can instead use the Application Insights Node.js SDK to send custom telemetry data to your Application Insights instance.

const appInsights = require("applicationinsights");
const client = appInsights.defaultClient;

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    // Use this with 'tagOverrides' to correlate custom telemetry to the parent function invocation.
    var operationIdOverride = {"":context.traceContext.traceparent};

    client.trackEvent({name: "my custom event", tagOverrides:operationIdOverride, properties: {customProperty2: "custom property value"}});
    client.trackException({exception: new Error("handled exceptions can be logged with this method"), tagOverrides:operationIdOverride});
    client.trackMetric({name: "custom metric", value: 3, tagOverrides:operationIdOverride});
    client.trackTrace({message: "trace message", tagOverrides:operationIdOverride});
    client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL", tagOverrides:operationIdOverride});
    client.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true, tagOverrides:operationIdOverride});


tagOverrides 参数将 operation_Id 设置为函数的调用 ID。The tagOverrides parameter sets the operation_Id to the function's invocation ID. 通过此设置,可为给定的函数调用关联所有自动生成的遥测和自定义遥测。This setting enables you to correlate all of the automatically generated and custom telemetry for a given function invocation.

HTTP 触发器和绑定HTTP triggers and bindings

HTTP 和 webhook 触发器以及 HTTP 输出绑定使用请求和响应对象来表示 HTTP 消息。HTTP and webhook triggers and HTTP output bindings use request and response objects to represent the HTTP messaging.

请求对象Request object

context.req(请求)对象具有以下属性:The context.req (request) object has the following properties:

属性Property 说明Description
bodybody 一个包含请求正文的对象。An object that contains the body of the request.
headersheaders 一个包含请求标头的对象。An object that contains the request headers.
methodmethod 请求的 HTTP 方法。The HTTP method of the request.
originalUrloriginalUrl 请求的 URL。The URL of the request.
paramsparams 一个包含请求的路由参数的对象。An object that contains the routing parameters of the request.
queryquery 一个包含查询参数的对象。An object that contains the query parameters.
rawBodyrawBody 字符串形式的消息正文。The body of the message as a string.

响应对象Response object

context.res(响应)对象具有以下属性:The context.res (response) object has the following properties:

属性Property 说明Description
bodybody 一个包含响应正文的对象。An object that contains the body of the response.
headersheaders 一个包含响应标头的对象。An object that contains the response headers.
isRawisRaw 指示是否为响应跳过格式设置。Indicates that formatting is skipped for the response.
statusstatus 响应的 HTTP 状态代码。The HTTP status code of the response.
cookiescookies 在响应中设置的 HTTP cookie 对象的数组。An array of HTTP cookie objects that are set in the response. HTTP cookie 对象有 namevalue 和其他 cookie 属性(如 maxAgesameSite)。An HTTP cookie object has a name, value, and other cookie properties, such as maxAge or sameSite.

访问请求和响应Accessing the request and response

使用 HTTP 触发器时,可采用多种方式来访问 HTTP 响应和请求对象:When you work with HTTP triggers, you can access the HTTP request and response objects in a number of ways:

  • 通过 context 对象的 reqres 属性。From req and res properties on the context object. 采用此方式时,可以使用传统模式通过上下文对象访问 HTTP 数据,而不必使用完整的 模式。In this way, you can use the conventional pattern to access HTTP data from the context object, instead of having to use the full pattern. 以下示例展示了如何访问 context 上的 reqres 对象:The following example shows how to access the req and res objects on the context:

    // You can access your HTTP request off the context ...
    if(context.req.body.emoji === ':pizza:') context.log('Yay!');
    // and also set your HTTP response
    context.res = { status: 202, body: 'You successfully ordered more coffee!' }; 
  • 通过已命名的输入和输出绑定。From the named input and output bindings. 采用此方式时,HTTP 触发器和绑定的工作方式与其他绑定相同。In this way, the HTTP trigger and bindings work the same as any other binding. 以下示例使用已命名的 response 绑定设置响应对象:The following example sets the response object by using a named response binding:

        "type": "http",
        "direction": "out",
        "name": "response"
    context.bindings.response = { status: 201, body: "Insert succeeded." };
  • [仅响应] 通过调用 context.res.send(body?: any)[Response only] By calling context.res.send(body?: any). HTTP 响应是使用输入 body 作为响应正文创建的。An HTTP response is created with input body as the response body. 隐式调用 context.done()context.done() is implicitly called.

  • [仅响应] 通过调用 context.done()[Response only] By calling context.done(). 有一种特殊类型的 HTTP 绑定可返回传递到 context.done() 方法的响应。A special type of HTTP binding returns the response that is passed to the context.done() method. 以下 HTTP 输出绑定定义了一个 $return 输出参数:The following HTTP output binding defines a $return output parameter:

      "type": "http",
      "direction": "out",
      "name": "$return"
     // Define a valid response object.
    res = { status: 201, body: "Insert succeeded." };
    context.done(null, res);   

缩放和并发Scaling and concurrency

默认情况下,Azure Functions 会自动监视应用程序上的负载,并按需为 Node.js 创建更多主机实例。By default, Azure Functions automatically monitors the load on your application and creates additional host instances for Node.js as needed. Functions 针对不同触发器类型使用内置(用户不可配置)阈值来确定何时添加实例,例如 QueueTrigger 的消息和队列大小。Functions uses built-in (not user configurable) thresholds for different trigger types to decide when to add instances, such as the age of messages and queue size for QueueTrigger. 有关详细信息,请参阅消耗计划和高级计划的工作原理For more information, see How the Consumption and Premium plans work.

此缩放行为足以满足多个 Node.js 应用程序的需求。This scaling behavior is sufficient for many Node.js applications. 对于占用大量 CPU 的应用程序,可使用多个语言工作进程进一步提高性能。For CPU-bound applications, you can improve performance further by using multiple language worker processes.

默认情况下,每个 Functions 主机实例都有一个语言工作进程。By default, every Functions host instance has a single language worker process. 使用 FUNCTIONS_WORKER_PROCESS_COUNT 应用程序设置可增加每个主机的工作进程数(最多 10 个)。You can increase the number of worker processes per host (up to 10) by using the FUNCTIONS_WORKER_PROCESS_COUNT application setting. 然后,Azure Functions 会尝试在这些工作进程之间平均分配同步函数调用。Azure Functions then tries to evenly distribute simultaneous function invocations across these workers.

FUNCTIONS_WORKER_PROCESS_COUNT 适用于 Functions 在横向扩展应用程序以满足需求时创建的每个主机。The FUNCTIONS_WORKER_PROCESS_COUNT applies to each host that Functions creates when scaling out your application to meet demand.

Node 版本Node version

下表按操作系统显示了 Functions 运行时的每个主版本当前支持的 Node.js 版本:The following table shows current supported Node.js versions for each major version of the Functions runtime, by operating system:

Functions 版本Functions version Node 版本 (Windows)Node version (Windows) Node 版本 (Linux)Node Version (Linux)
3.x(建议)3.x (recommended) ~14(推荐)~14 (recommended)
node|14(推荐)node|14 (recommended)
2.x2.x ~12
1.x1.x 6.11.2(运行时锁定)6.11.2 (locked by the runtime) 不适用n/a

可以通过从任何函数中记录 process.version 来查看运行时使用的当前版本。You can see the current version that the runtime is using by logging process.version from any function.

设置 Node 版本Setting the Node version

对于 Windows 函数应用,通过将 WEBSITE_NODE_DEFAULT_VERSION 应用设置设为受支持的 LTS 版本(例如 ~14)来针对 Azure 中的版本进行操作。For Windows function apps, target the version in Azure by setting the WEBSITE_NODE_DEFAULT_VERSION app setting to a supported LTS version, such as ~14.

对于 Linux 函数应用,请运行以下 Azure CLI 命令更新 Node 版本。For Linux function apps, run the following Azure CLI command to update the Node version.

az functionapp config set --linux-fx-version "node|14" --name "<MY_APP_NAME>" --resource-group "<MY_RESOURCE_GROUP_NAME>"

依赖项管理Dependency management

若要在 JavaScript 代码中使用社区库(如下面的示例所示),需要确保在 Azure 中的 Function App 上安装所有依赖项。In order to use community libraries in your JavaScript code, as is shown in the below example, you need to ensure that all dependencies are installed on your Function App in Azure.

// Import the underscore.js library
var _ = require('underscore');
var version = process.version; // version === 'v6.5.0'

module.exports = function(context) {
    // Using our imported underscore.js library
    var matched_names = _
        .where(context.bindings.myInput.names, {first: 'Carla'});


应当在 Function App 的根目录下定义一个 package.json 文件。You should define a package.json file at the root of your Function App. 定义该文件将允许应用中的所有函数共享所缓存的相同包,从而获得最佳性能。Defining the file lets all functions in the app share the same cached packages, which gives the best performance. 如果发生版本冲突,可以通过在具体函数的文件夹中添加一个 package.json 文件来解决冲突。If a version conflict arises, you can resolve it by adding a package.json file in the folder of a specific function.

部署过程中,从源控件中部署 Function App 时,存储库中存在的任何 package.json 文件都将在其文件夹中触发 npm installWhen deploying Function Apps from source control, any package.json file present in your repo, will trigger an npm install in its folder during deployment. 但在通过门户或 CLI 部署时,必须手动安装包。But when deploying via the Portal or CLI, you will have to manually install the packages.

可通过两种方法在 Function App 上安装包:There are two ways to install packages on your Function App:

使用依赖项部署Deploying with Dependencies

  1. 通过运行 npm install 在本地安装所有必需的包。Install all requisite packages locally by running npm install.

  2. 部署代码,并确保部署中包含 node_modules 文件夹。Deploy your code, and ensure that the node_modules folder is included in the deployment.

使用 KuduUsing Kudu

  1. 转到 https://<function_app_name>.scm.chinacloudsites.cnGo to https://<function_app_name>

  2. 单击“调试控制台”,选择“CMD”。 > Click Debug Console > CMD.

  3. 转到 D:\home\site\wwwroot,然后将 package.json 文件拖到页面上半部分中的 wwwroot 文件夹上。Go to D:\home\site\wwwroot, and then drag your package.json file to the wwwroot folder at the top half of the page.
    还可采用其他方式将文件上传到 Function App。You can upload files to your function app in other ways also. 有关详细信息,请参阅如何更新 Function App 文件For more information, see How to update function app files.

  4. 上传 package.json 文件后,在 Kudu 远程执行控制台 中运行 npm install 命令。After the package.json file is uploaded, run the npm install command in the Kudu remote execution console.
    此操作将下载 package.json 文件中指定的包并重新启动 Function App。This action downloads the packages indicated in the package.json file and restarts the function app.

环境变量Environment variables

在本地环境和云环境中,向函数应用添加你自己的环境变量,如操作机密(连接字符串、密钥和终结点)或环境设置(例如分析变量)。Add your own environment variables to a function app, in both your local and cloud environments, such as operational secrets (connection strings, keys, and endpoints) or environmental settings (such as profiling variables). 在函数代码中使用 process.env 访问这些设置。Access these settings using process.env in your function code.

在本地开发环境中In local development environment

在本地运行时,函数项目包括一个 local.settings.json 文件,你可以在其中将环境变量存储到 Values 对象中。When running locally, your functions project includes a local.settings.json file, where you store your environment variables in the Values object.

  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "translatorTextEndPoint": "",
    "translatorTextKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "languageWorkers__node__arguments": "--prof"

在 Azure 云环境中In Azure cloud environment

在 Azure 中运行时,函数应用允许你使用应用程序设置(例如服务连接字符串),并在执行期间将这些设置作为环境变量公开。When running in Azure, the function app lets you set uses Application settings, such as service connection strings, and exposes these settings as environment variables during execution.

可以通过以下几种方法添加、更新和删除函数应用设置:There are several ways that you can add, update, and delete function app settings:

如果更改函数应用设置,则需要重启函数应用。Changes to function app settings require your function app to be restarted.

在代码中访问环境变量Access environment variables in code

使用 process.env 将应用程序设置作为环境变量访问,如此处对 context.log() 的第二次和第三次调用所示,其中记录了 AzureWebJobsStorageWEBSITE_SITE_NAME 环境变量:Access application settings as environment variables using process.env, as shown here in the second and third calls to context.log() where we log the AzureWebJobsStorage and WEBSITE_SITE_NAME environment variables:

module.exports = async function (context, myTimer) {

    context.log("AzureWebJobsStorage: " + process.env["AzureWebJobsStorage"]);
    context.log("WEBSITE_SITE_NAME: " + process.env["WEBSITE_SITE_NAME"]);

ECMAScript 模块(预览)ECMAScript modules (preview)


由于 ECMAScript 模块当前在 Node.js 14 标记为“试验”,因此在 Node.js 14 Azure Functions 中可将其作为预览功能提供。As ECMAScript modules are currently labeled experimental in Node.js 14, they're available as a preview feature in Node.js 14 Azure Functions. 在 Node.js 14 对 ECMAScript 模块的支持变为“稳定”之前,可能会对其 API 或行为进行更改。Until Node.js 14 support for ECMAScript modules becomes stable, expect possible changes to its API or behavior.

ECMAScript 模块(ES 模块)是 Node.js 的新官方标准模块系统。ECMAScript modules (ES modules) are the new official standard module system for Node.js. 到目前为止,本文中的代码示例使用 CommonJS 语法。So far, the code samples in this article use the CommonJS syntax. 在 Node.js 14 中运行 Azure Functions 时,可以选择使用 ES 模块语法编写函数。When running Azure Functions in Node.js 14, you can choose to write your functions using ES modules syntax.

若要在函数中使用 ES 模块,请将其文件名更改为使用 .mjs 扩展名。To use ES modules in a function, change its filename to use a .mjs extension. 下面的 index.mjs 文件示例是一个 HTTP 触发函数,它使用 ES 模块语法导入 uuid 库并返回值。The following index.mjs file example is an HTTP triggered function that uses ES modules syntax to import the uuid library and return a value.

import { v4 as uuidv4 } from 'uuid';

export default async function (context, req) {
    context.res.body = uuidv4();

配置函数入口点Configure function entry point

function.json 属性 scriptFileentryPoint 可用于配置导出函数的位置和名称。The function.json properties scriptFile and entryPoint can be used to configure the location and name of your exported function. 转译 JavaScript 时,这些属性可能非常重要。These properties can be important when your JavaScript is transpiled.

使用 scriptFileUsing scriptFile

默认情况下通过 index.js(与其对应的 function.json 共享相同父目录的文件)执行 JavaScript 函数。By default, a JavaScript function is executed from index.js, a file that shares the same parent directory as its corresponding function.json.

scriptFile 可用于获取以下示例所示的文件夹结构:scriptFile can be used to get a folder structure that looks like the following example:

 | - host.json
 | - myNodeFunction
 | | - function.json
 | - lib
 | | - sayHello.js
 | - node_modules
 | | - ... packages ...
 | - package.json

myNodeFunctionfunction.json 应包含 scriptFile 属性,该属性指向包含要运行的导出函数的文件。The function.json for myNodeFunction should include a scriptFile property pointing to the file with the exported function to run.

  "scriptFile": "../lib/sayHello.js",
  "bindings": [

使用 entryPointUsing entryPoint

scriptFile(或 index.js)中,必须使用 module.exports 导出函数才能使其被找到和运行。In scriptFile (or index.js), a function must be exported using module.exports in order to be found and run. 默认情况下,触发时执行的函数是该文件的唯一导出(导出名为 runindex)。By default, the function that executes when triggered is the only export from that file, the export named run, or the export named index.

可以使用 function.json 中的 entryPoint 配置此项设置,如以下示例所示:This can be configured using entryPoint in function.json, as in the following example:

  "entryPoint": "logFoo",
  "bindings": [

Functions v2.x 支持用户函数中的 this 参数,其中的函数代码可能如以下示例所示:In Functions v2.x, which supports the this parameter in user functions, the function code could then be as in the following example:

class MyObj {
    constructor() { = 1;

    logFoo(context) { 
        context.log("Foo is " +; 

const myObj = new MyObj();
module.exports = myObj;

请在此示例中务必注意,尽管正在导出对象,但无法保证可保留两次执行之间的状态。In this example, it is important to note that although an object is being exported, there are no guarantees for preserving state between executions.

本地调试Local Debugging

使用 --inspect 参数启动时,Node.js 进程会在指定端口上侦听调试客户端。When started with the --inspect parameter, a Node.js process listens for a debugging client on the specified port. 在 Azure Functions 2.x 中,可以指定要传递到运行代码的 Node.js 进程中的参数,方法是添加环境变量或应用设置 languageWorkers:node:arguments = <args>In Azure Functions 2.x, you can specify arguments to pass into the Node.js process that runs your code by adding the environment variable or App Setting languageWorkers:node:arguments = <args>.

若要在本地进行调试,请在 local.settings.json 文件的 Values 下添加 "languageWorkers:node:arguments": "--inspect=5858",然后将调试程序附加到端口 5858。To debug locally, add "languageWorkers:node:arguments": "--inspect=5858" under Values in your local.settings.json file and attach a debugger to port 5858.

使用 VS Code 进行调试时,系统会使用项目的 launch.json 文件中的 port 值自动添加 --inspect 参数。When debugging using VS Code, the --inspect parameter is automatically added using the port value in the project's launch.json file.

在版本 1.x 中,设置 languageWorkers:node:arguments 将无效。In version 1.x, setting languageWorkers:node:arguments will not work. 可以在 Azure Functions Core Tools 中使用 --nodeDebugPort 参数来选择调试端口。The debug port can be selected with the --nodeDebugPort parameter on Azure Functions Core Tools.


如果将目标限定为 2.x 版 Functions 运行时,可以在 Azure Functions for Visual Studio CodeAzure Functions Core Tools 中使用支持 TypeScript 函数应用项目的模板创建函数应用。When you target version 2.x of the Functions runtime, both Azure Functions for Visual Studio Code and the Azure Functions Core Tools let you create function apps using a template that support TypeScript function app projects. 该模板会生成 package.jsontsconfig.json 项目文件,以方便使用这些工具从 TypeScript 代码转译、运行和发布 JavaScript 函数。The template generates package.json and tsconfig.json project files that make it easier to transpile, run, and publish JavaScript functions from TypeScript code with these tools.

生成的 .funcignore 文件用于指示将项目发布到 Azure 时会排除哪些文件。A generated .funcignore file is used to indicate which files are excluded when a project is published to Azure.

TypeScript 文件 (.ts) 转译为 dist 输出目录中的 JavaScript (.js) 文件。TypeScript files (.ts) are transpiled into JavaScript files (.js) in the dist output directory. TypeScript 模板使用 function.json 中的 scriptFile 参数来指示 dist 文件夹中相应 .js 文件的位置。TypeScript templates use the scriptFile parameter in function.json to indicate the location of the corresponding .js file in the dist folder. 模板使用 tsconfig.json 文件中的 outDir 参数设置输出位置。The output location is set by the template by using outDir parameter in the tsconfig.json file. 如果更改此设置或文件夹的名称,则运行时将找不到要运行的代码。If you change this setting or the name of the folder, the runtime is not able to find the code to run.

在本地通过 TypeScript 项目进行开发和部署的方式取决于所用的开发工具。The way that you locally develop and deploy from a TypeScript project depends on your development tool.

Visual Studio CodeVisual Studio Code

Azure Functions for Visual Studio Code 扩展允许使用 TypeScript 开发函数。The Azure Functions for Visual Studio Code extension lets you develop your functions using TypeScript. Azure Functions 扩展要求安装 Core Tools。The Core Tools is a requirement of the Azure Functions extension.

若要在 Visual Studio Code 中创建 TypeScript 函数应用,请在创建函数应用时选择 TypeScript 作为语言。To create a TypeScript function app in Visual Studio Code, choose TypeScript as your language when you create a function app.

按下 F5 在本地运行应用时,会先执行转译,然后再初始化主机 (func.exe)。When you press F5 to run the app locally, transpilation is done before the host (func.exe) is initialized.

使用“部署到函数应用...”按钮将函数应用部署到 Azure 时,Azure Functions 扩展首先会基于 TypeScript 源文件生成一个可随时在生产环境中使用的 JavaScript 文件版本。When you deploy your function app to Azure using the Deploy to function app... button, the Azure Functions extension first generates a production-ready build of JavaScript files from the TypeScript source files.

Azure Functions Core ToolsAzure Functions Core Tools

使用 Core Tools 时,TypeScript 项目与 JavaScript 项目有几种不同之处。There are several ways in which a TypeScript project differs from a JavaScript project when using the Core Tools.

创建项目Create project

若要使用 Core Tools 创建 TypeScript 函数应用项目,必须在创建函数应用时指定 TypeScript 语言选项。To create a TypeScript function app project using Core Tools, you must specify the TypeScript language option when you create your function app. 可通过以下方式之一执行此操作:You can do this in one of the following ways:

  • 运行 func init 命令,选择 node 作为语言堆栈,然后选择 typescriptRun the func init command, select node as your language stack, and then select typescript.

  • 运行 func init --worker-runtime typescript 命令。Run the func init --worker-runtime typescript command.

在本地运行Run local

若要使用 Core Tools 在本地运行函数应用代码,请使用以下命令而不是 func host startTo run your function app code locally using Core Tools, use the following commands instead of func host start:

npm install
npm start

npm start 命令等效于以下命令:The npm start command is equivalent to the following commands:

  • npm run build
  • func extensions install
  • tsc
  • func start

发布到 AzurePublish to Azure

在使用 func azure functionapp publish 命令部署到 Azure 之前,请基于 TypeScript 源文件创建一个随时可在生产环境中使用的 JavaScript 文件版本。Before you use the func azure functionapp publish command to deploy to Azure, you create a production-ready build of JavaScript files from the TypeScript source files.

以下命令使用 Core Tools 准备和发布 TypeScript 项目:The following commands prepare and publish your TypeScript project using Core Tools:

npm run build:production 
func azure functionapp publish <APP_NAME>

在此命令中,将 <APP_NAME> 替换为函数应用的名称。In this command, replace <APP_NAME> with the name of your function app.

JavaScript 函数的注意事项Considerations for JavaScript functions

使用 JavaScript 函数时,请注意以下各节中的注意事项。When you work with JavaScript functions, be aware of the considerations in the following sections.

选择单 vCPU 应用服务计划Choose single-vCPU App Service plans

创建使用应用服务计划的函数应用时,建议选择单 vCPU 计划,而不是选择具有多个 vCPU 的计划。When you create a function app that uses the App Service plan, we recommend that you select a single-vCPU plan rather than a plan with multiple vCPUs. 目前,Functions 在单 vCPU VM 上运行 JavaScript 函数更为高效;使用更大的 VM 不会产生预期的性能提高。Today, Functions runs JavaScript functions more efficiently on single-vCPU VMs, and using larger VMs does not produce the expected performance improvements. 需要时,可以通过添加更多单 vCPU VM 实例来手动横向扩展,也可以启用自动缩放。When necessary, you can manually scale out by adding more single-vCPU VM instances, or you can enable autoscale. 有关详细信息,请参阅手动或自动缩放实例计数For more information, see Scale instance count manually or automatically.

冷启动Cold Start

对于无服务器托管模型中开发 Azure Functions,冷启动已成为现实。When developing Azure Functions in the serverless hosting model, cold starts are a reality. “冷启动”是指在函数应用处于非活动状态一段时间后进行第一次启动时,将需要较长时间才能启动。Cold start refers to the fact that when your function app starts for the first time after a period of inactivity, it takes longer to start up. 具体而言,对于具有较大依赖项树的 JavaScript 函数,冷启动可能不足以解决问题。For JavaScript functions with large dependency trees in particular, cold start can be significant. 为了加快冷启动过程,请尽量以包文件的形式运行函数To speed up the cold start process, run your functions as a package file when possible. 许多部署方法默认使用包模型中的运行,但如果遇到大规模的冷启动而不是以这种方式运行,则此项更改可以提供明显的改善。Many deployment methods use the run from package model by default, but if you're experiencing large cold starts and are not running this way, this change can offer a significant improvement.

连接限制Connection Limits

在 Azure Functions 应用程序中使用特定于服务的客户端时,不要在每次函数调用时都创建新的客户端。When you use a service-specific client in an Azure Functions application, don't create a new client with every function invocation. 而是,应在全局范围内创建单个静态客户端。Instead, create a single, static client in the global scope. 有关详细信息,请参阅在 Azure Functions 中管理连接For more information, see managing connections in Azure Functions.

使用 asyncawaitUse async and await

在 JavaScript 中编写 Azure Functions 时,应使用 asyncawait 关键字编写代码。When writing Azure Functions in JavaScript, you should write code using the async and await keywords. 使用 asyncawait 编写代码,而不是使用回调或者结合约定使用 .then.catch,将有助于避免两个常见问题:Writing code using async and await instead of callbacks or .then and .catch with Promises helps avoid two common problems:

  • 引发未经捕获的异常,从而导致 Node.js 进程崩溃,并可能影响其他函数的执行。Throwing uncaught exceptions that crash the Node.js process, potentially affecting the execution of other functions.
  • 意外的行为,例如,未正常等待的异步调用导致 context.log 中缺少日志。Unexpected behavior, such as missing logs from context.log, caused by asynchronous calls that are not properly awaited.

以下示例使用错误优先回调函数作为第二个参数调用异步方法 fs.readFileIn the example below, the asynchronous method fs.readFile is invoked with an error-first callback function as its second parameter. 此代码会导致出现上述两个问题。This code causes both of the issues mentioned above. 未在正确范围内显式捕获的异常导致整个进程崩溃(问题 #1)。An exception that is not explicitly caught in the correct scope crashed the entire process (issue #1). 在回调函数范围以外调用 context.done() 意味着函数调用可能会在读取文件之前结束(问题 #2)。Calling context.done() outside of the scope of the callback function means that the function invocation may end before the file is read (issue #2). 在此示例中,过早调用 context.done() 导致缺少以 Data from file: 开头的日志条目。In this example, calling context.done() too early results in missing log entries starting with Data from file:.

const fs = require('fs');

module.exports = function (context) {
    fs.readFile('./hello.txt', (err, data) => {
        if (err) {
            context.log.error('ERROR', err);
            // BUG #1: This will result in an uncaught exception that crashes the entire process
            throw err;
        context.log(`Data from file: ${data}`);
        // context.done() should be called here
    // BUG #2: Data is not guaranteed to be read before the Azure Function's invocation ends

使用 asyncawait 关键字有助于避免这两个错误。Using the async and await keywords helps avoid both of these errors. 应使用 Node.js 实用工具函数 util.promisify 将错误优先回调样式函数转换为可等待函数。You should use the Node.js utility function util.promisify to turn error-first callback-style functions into awaitable functions.

在以下示例中,在执行函数过程中引发的任何未经处理的异常只会导致引发异常的单个调用失败。In the example below, any unhandled exceptions thrown during the function execution only fail the individual invocation that raised an exception. await 关键字表示只有在完成 readFile 后,才执行 readFileAsync 后面的步骤。The await keyword means that steps following readFileAsync only execute after readFile is complete. 此外,如果使用 asyncawait,则无需调用 context.done() 回调。With async and await, you also don't need to call the context.done() callback.

// Recommended pattern
const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);

module.exports = async function (context) {
    let data;
    try {
        data = await readFileAsync('./hello.txt');
    } catch (err) {
        context.log.error('ERROR', err);
        // This rethrown exception will be handled by the Functions Runtime and will only fail the individual invocation
        throw err;
    context.log(`Data from file: ${data}`);

后续步骤Next steps

有关详细信息,请参阅以下资源:For more information, see the following resources: